I would like to iterate thru each of the students and then excecute two query which the execution of these two queries should be sync, first one first then since the second query depends on the first.
I have written some code but it does not seem working at all:
Student.find({ status: 'student' })
.populate('student')
.exec(function (err, students) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
_.forEach(students, function (student) {
async.waterfall(
[
function (callback) {
console.log('first ' + student.firstName);
Student.find({ "_id": student.id }, callback);
},
function (student, callback) {
console.log('second '+ student[0].firstName);
WorksnapsTimeEntry.find({
"student": {
"$in": student.map(function (el) {
return el._id
})
}
}, callback);
}
],
function (err, results) {
if (err) {
// do something
} else {
// results are the matching entries
console.log('third');
var totalMinutes = 0;
var totalAvgLevelActivity = 0;
var counter = 0;
_.forEach(results, function (item) {
_.forEach(item.timeEntries, function (item) {
if (item.duration_in_minutes) {
totalMinutes = totalMinutes + parseFloat(item.duration_in_minutes[0]);
}
if (item.activity_level) {
totalAvgLevelActivity = totalAvgLevelActivity + parseFloat(item.activity_level[0]);
counter++;
}
});
});
var obj = {};
obj.studentId = 'test';
obj.firstName = 'test';
obj.lastName = 'test';
obj.municipality = 'test';
obj.totalMinutes = totalMinutes;
obj.totalAvgLevelActivity = totalAvgLevelActivity / counter;
arrayReports.push(obj);
// console.log('not yet finished.');
}
}
);
});
res.json(arrayReports);
console.log('finished.');
Anyone has an idea how do I achieve this thing in Node.js
async.waterfallwrong. From each of the task functions, you need to call the next function with suitable arguments