I guess it should be simple for those who familiar with Node.js and Mongoose. I'm trying to get the final result inside async forEach and mongoose find, I can see the results fine in the middle of the function, but when Im trying to get it after the second forEach, I cant.
I have tried to catch the last iteration and bring the results back, but because its async, the last iteration arrived before the find in the middle of the function.
Any suggestions? Here is what I have:
function addUsersInfoForEachVote(req, res, next){
var itemsProcessed = 0;
Questions.findOne({_id: req.body.question}, {answers: 1}).exec(function (err, question) {
var finalVotes = [];
if (err | !question) {
return res.send({
errors: err | "No Question Found"
});
} else {
question.answers.forEach((answer, index, array) => {
var votedUsers = [];
votedUsers = votedUsers.concat(answer.get("votes"));
answer._doc.votes = answer.get("votes").length;
var ansId = answer.answerId;
var aData = {answer: answer, users: {}};
AnswersVote.find({'_id': {$in: getUniqueIds(votedUsers)}},{user: 1})
.populate('user', 'name gender')
.exec(function(err, votesUsers){
if (!err) {
votesUsers.forEach(function(vote){
var user = vote.get("user");
if (user){
aData.users[user.get("id")] = user;
}
});
console.log("ADATA:"+JSON.stringify(aData)); //Here I can see it well! (the second time contain it all)
}
});
//currAns = votedUsers;
itemsProcessed++;
if( itemsProcessed === array.length) {
//HERE I NEED THE FINAL RESULTS:
console.log("ADATA after:"+JSON.stringify(aData));
next();
}
});
}
});
}
if (err | !question)to justif (err)(if you want to use that anyway, the correct syntax isif (err || !question)