Trong Lam Phan Trong Lam Phan - 4 months ago 8
Node.js Question

Mongoosejs use promise in a for loop

I have two collections: question and answer. Each answer belongs to a question so an answer has its "question_id".

I like to get five questions which has most answers:

Answer.aggregate([
{
$group: {
_id: '$question_id',
num_questions: { $sum: 1 },
}
},
{
$sort: {
'num_questions': -1
}
}
]).then(function(answers) {
var result = [];
for(answer of answers) {
Question.findById(answer._id, function(err, question) {
result.push(question);
});
}
console.log(result);
res.json({questions: result});
});


but with the above code, my result will be null because of the async mechanism.

How can i get it done ?

Another problem that i had, with the aggregate query, i can only have questions that has at least one answer. How can i get the questions without answer ?

Thank you !

Answer
Answer.aggregate([
        {
            $group: {
                _id: '$question_id',
                num_questions: { $sum: 1 },
            }
        },
        {
            $sort: {
                'num_questions': -1
            }
        }
    ]).then(function(answers) {
        var result = [];
        var count = 0;
        for(answer of answers) {
            Question.findById(answer._id, function(err, question) {
         count++
                result.push(question);
       if (count == 5) {
        res.json({questions: result});
      }
            });
        }
        console.log(result);
});