我正在使用node-js,mongoose和express创建一个Web应用程序。我有特定月份特定雇员的详细信息(出勤详细信息),并且我从前端下拉列表中选择的选项来获取该月所有雇员的详细信息。获得这些文档后,我需要找到具有不同员工编号的员工。回调中的变量'docs'由特定月份的所有员工详细信息文档组成,我只需要从这些文档中找到不同的员工编号。 / p>
app.get("/getSummary",(req,res)=>{
console.log(req.query.substr);
Attendance.find({
"date":{
"$regex":req.query.substr,
"$options": "i"
}
}).then((docs)=>{
if(docs.length == 0){
console.log("empty");
return res.status(404).send('No records for selected month found');
}
console.log("check: ",docs);
var responseArr=[];
res.status(200).send(docs);
}).catch((err)=>{
res.status(404).send(err);
});
});
答案 0 :(得分:0)
假设您有“雇员”集合和“出勤”集合,其雇员名为“ Id”。 员工文档如下所示:
[
{_id:"1",name:"John Doe",...},
{_id:"2",name:"Alex Foo",...},
{_id:"3",name:"James Bar",...},
]
和出勤集合如下:
[
{date:'2019-06-22',employeeId:"1",start:"07:00:00 AM",end:"04:00:00 PM"},
{date:'2019-06-22',employeeId:"2",start:"07:10:00 AM",end:"04:00:00 PM"},
{date:'2019-06-22',employeeId:"3",start:"08:00:00 AM",end:"04:00:00 PM"},
{date:'2019-06-23', employeeId:"1",start:"07:05:00 AM",end:"04:00:00 PM"},
{date:'2019-06-23', employeeId:"2",start:"07:20:00 AM",end:"04:00:00 PM"},
{date:'2019-06-23', employeeId:"3",start:"07:00:00 AM",end:"04:00:00 PM"},
]
如果您需要在一个月内获取每位用户的所有记录,那么您将需要进行汇总,例如:
Attendance.aggregate([
{
$match: {
"date": {
$gte: new Date("2019-06-01"),
$lt: new Date("2019-06-30")
}
}
},
{
$group:{
_id:"$employeeId",
Attendance:{
$addToSet:{
date :"$date" ,
start: "$start",
end: "$end",
}
}
}
},
{
$lookup: {
from: "employee",
localField: "_id",
foreignField: "_id",
as: "Employee"
}
},
])
这将返回如下结果:
[
{
_id:"1",
Employee:{_id:"1",name:"John Doe",....}
Attendance:[
{date:'2019-06-22',start:"07:00:00 AM",end:"04:00:00 PM"},
{date:'2019-06-23',,start:"07:05:00 AM",end:"04:00:00 PM"},
...
],
},
{
_id:"2",
Employee:{_id:"2",name:"Alex Foo",....}
Attendance:[
{date:'2019-06-22',start:"07:10:00 AM",end:"04:00:00 PM"},
{date:'2019-06-23',start:"07:20:00 AM",end:"04:00:00 PM"},
...
],
},
.... And so on
]
我假定了大部分架构结构,因为您没有在问题中对其进行定义,希望对您有所帮助