我在API中使用嵌套循环。一个循环对于循环来说很简单,另一个循环是异步的Foreach循环,执行时会输出重复的记录
我使用一个简单的函数来循环遍历迭代,但它会停止数组迭代。
var loop_array = ["2019-06-13", "2019-06-14", "2019-06-15", "2019-06-16", "2019-06-17"]
try {
var users = await User.find({ 'roles': "employee" });
await forEach(users, async user_data => {
employee_result = [];
//await loopArray(loop_array, user_data._id);
for (let element of loop_array) {
let date2 = moment(element).add(1, 'days').format("YYYY-MM-DD");
let employee_attendance = await Attendance.findOne({
$and: [
{ "actual_checkin": { $gte: element } },
{ "actual_checkin": { $lt: date2 } },
{ "employee": user_data._id }
]
});
var data = {
dates: element,
employee_attendance: employee_attendance
}
employee_result.push(data);
}
var employee_data = {
"employee": user_data.name,
"employee_data": employee_result
};
employee_result2.push(employee_data);
});
} catch (e) {
console.log(e);
}
此代码是重复记录的重复
for (let element of loop_array) {
let date2 = moment(element).add(1, 'days').format("YYYY-MM-DD");
let employee_attendance = await Attendance.findOne({
$and: [
{ "actual_checkin": { $gte: element } },
{ "actual_checkin": { $lt: date2 } },
{ "employee": user_data._id }
]
});
var data = {
dates: element,
employee_attendance: employee_attendance
}
employee_result.push(data);
}
重复迭代的Json响应
{
"employee_payroll": [
{
"employee": "Test Password",
"employee_data": [
{
"dates": "2019-06-13",
"employee_attendance": {
"status": 0,
"_id": "5d01dd5ea241427c0a43f273",
"employee": "5d00ad8592ab136ee97d5252",
"booking": "5d00aec092ab136ee97d5261",
"schedule_id": "5d00aea492ab136ee97d525f",
"minor_checkin_checkout": [],
"main_radius_checkin": "2019-06-13T05:20:43.884Z",
"main_radius_checkout": "2019-06-13T05:21:33.328Z",
"actual_checkin": "2019-06-13T05:20:58.794Z",
"actual_checkout": "2019-06-13T05:21:33.328Z",
"__v": 0
}
},
{
"dates": "2019-06-13",
"employee_attendance": null
},
{
"dates": "2019-06-13",
"employee_attendance": null
},
{
"dates": "2019-06-14",
"employee_attendance": null
},
{
"dates": "2019-06-13",
"employee_attendance": null
},
]
}
预期的json响应
{
"employee_payroll": [
{
"employee": "Test Password",
"employee_data": [
{
"dates": "2019-06-13",
"employee_attendance": {
"status": 0,
"_id": "5d01dd5ea241427c0a43f273",
"employee": "5d00ad8592ab136ee97d5252",
"booking": "5d00aec092ab136ee97d5261",
"schedule_id": "5d00aea492ab136ee97d525f",
"minor_checkin_checkout": [],
"main_radius_checkin": "2019-06-13T05:20:43.884Z",
"main_radius_checkout": "2019-06-13T05:21:33.328Z",
"actual_checkin": "2019-06-13T05:20:58.794Z",
"actual_checkout": "2019-06-13T05:21:33.328Z",
"__v": 0
}
},
{
"dates": "2019-06-14",
"employee_attendance": null
},
{
"dates": "2019-06-15",
"employee_attendance": null
},
{
"dates": "2019-06-16",
"employee_attendance": null
},
{
"dates": "2019-06-17",
"employee_attendance": null
},
]
}