im试图计算vacations
集合中每个文档的endDate
和startDate
之间的差异,以找到employee
有多少假期?:
const employee = await Employee.findOne({ nameAR: req.body.name });
const vacations = await Vacation.find({ employeeId: employee._id });
let numberOfDays = 0;
vacations.map((vacation) => {
Vacation.aggregate([
{
$project: {
_id: vacation._id,
start: vacation.startDate,
end: vacation.endDate,
result: {
$subtract: ["$end", "$start"],
},
},
},
]).exec(function (err, diff) {
vacationCount.numberOfDays = vacationCount.numberOfDays + diff;
});
});
map
为employee
和aggregate
循环vacations
数组,以查找每个vacation
文档的日期之间的差异,将其存储在变量numberOfDay
中,并添加下一个。
我有两个问题:第一个:exec
方法返回一个对象数组,我不想要它,我只希望它返回result
,因为我不想再次映射
第二个也是大的:result
返回null
,这意味着aggregate
甚至不能正常工作
我已经确保employee
和vacations
数据成功地提取
注意:startDate
和endDate
在某些文档中可能是null
。
假期返回的文档将是这样的:
[
{
"_id": "631b59a8f25e201029953b31",
"employeeId": "631b595578dae2d46f112389",
"type": "Annual",
"startDate": "2022-09-09T00:00:00.000Z",
"endDate": "2022-09-14T00:00:00.000Z",
"numberOfHours": null,
"status": "approved",
"__v": 0
},
{
"_id": "631b59d9f25e201029953b3d",
"employeeId": "631b595578dae2d46f112389",
"type": "Day time leave",
"startDate": null,
"endDate": null,
"numberOfHours": "4",
"status": "approved",
"__v": 0
},
{
"_id": "631b59dbf25e201029953b40",
"employeeId": "631b595578dae2d46f112389",
"type": "Day time leave",
"startDate": null,
"endDate": null,
"numberOfHours": "5",
"status": "approved",
"__v": 0
},
]
提前感谢
试试这个,告诉我它是否适合你:
// Finding particular Employee details from employee collection
const employee = await Employee.findOne({ nameAR: req.body.name });
// Stores Total Number of Vacation Days
let numberOfDay = 0;
/* Finding all matching vacation records from vaction collection,aggregate them
and calculate no. of days between end and start date, stores it to numberOfVacationDays.*/
const vacations = await Vacation.aggregate([
{
$project: {
_id: "$_id",
start: "$startDate",
end: "$endDate",
numberOfVacationDays: {
$divide: [
{
$subtract: [
{
"$toDate": "$endDate"
},
{
"$toDate": "$startDate"
}
]
},
//returned mills can be converted to day by dividing by 86400000 (number of milliseconds in 24 hours)
86400000
]
},
},
},
{
"$match": {
employeeId: employee._id
}
}
]).exec();
// Once we have all vacation days of employee ,
//we can calculate total Number Of Vacation Days and store it in numberOfDay
vacations.forEach((vacation) =>{
if(vacation.numberOfVacationDays){
numberOfDay += vacation.numberOfVacationDays;
}
});