Here's a snippet of code from my router:
router.get('/questions/best', function(req, res, next) {
Question.aggregate([
// Include data protection measures with $ifNull and max[$size,1]
{$project: {ratio: {$divide:[
{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
{$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
]}},
{$sort: {ratio: -1}},
{$limit: 15}
]).exec(function(err, results) {
if (err) {return next(err)}
let top15 = [];
for(let i = 0; i < results.length; i++) {
Question.findOne({_id: results[i]._id}).exec(function(err, result) {
if (err) {return next(err)}
top15.push(result);
if (top15.length === results.length) {
res.render('content', { whichOne: 5, user: req.user, questions: top15 });
}
})
}
});
});
I'm facing an issue where the template gets rendered automatically before all queries are completed, causing incomplete data to be displayed. I've tried using setTimeout but it's not reliable due to varying processing times. Is there a way to ensure that the template is rendered only after all queries have returned and their values are populated in the array? Any suggestions or help would be greatly appreciated. Thank you!