我创建了一个应用程序来存储组织中员工的出勤情况。每个员工属于不同的部门。挑战是,我试图弄清楚如何使用 mongoose 查询 MongoDB,以便获得特定部门中存在的总数的 7 天数据。
我尝试使用以下内容,但无法找出将产生我想要的结果的查询:
const d =new Date();
d.setDate(d.getDate()-7); ....//7days record
db.user.aggregate(["required query here"])... //record based on query
我在 mongoose 和 Nodejs 方面并没有太多经验,只是基础知识。
这是我的 MongoDB 数据库/集合中存储的信息
{ //extracted from my mongoDB database
"_id": "5d40c2a35a6da12cd8506fac",
"name": "Jonhny Fredicks",
"department": "Marketing", //department is first criteria
"origin": "N/Y",
"joinDate": "2019-07-30",
"__v": 0,
"attendances": {
// attendance is second criteria
"2019-07-30": "Present",// total number of "present" is the final goal.This would be done for all employee with the same "department" field.
"2019-07-31": "Sick",
"2019-08-01": "Present",
"2019-08-02": "Present",
"2019-08-06": "Present",
"2019-08-08": "Vacation",
"2019-08-10": "Present",
"2019-08-12": "Sick",
"2019-08-21": "Present"
}
我非常感谢您的建议:我的目标是能够获取过去 7 天内在场的员工记录,将其发送到前端,在那里我将使用该数字乘以他们输入的小时费率。因此计算他们一周的工资。
最佳答案
遵循这一点,希望您能够找到 9 天中最近 7 天工作的员工。
router.get("/api",(req,res,next)=>{
db.find().then((result)=>{
var js=[];
for(var a = 0;a<result.length;a++){
obj=result[a];
var counter =0;
var name= Object.getOwnPropertyNames(obj.attendances);
for(var i=0;i<name.length;i++){
if(obj.attendances[name[i]]=="Present"){
counter +=1;
}
}
if(counter>=7){
js.push(obj);
console.log("Okay")
}else{
console.log("It's not okay")
}
}
console.log(js);
res.json({data:js});
});
});
关于node.js - 如何使用 Nodejs 对从 mongoDB 获取的数据求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610872/