I want to query two separate and different things to mongodb using Mongoose and ajax asynchronously.
Here is the code:
var teams, faculties;
userModel.find({}).sort('-score').exec((err, result) => {
teams = result;
});
userModel.aggregate([{
"$group": {
_id: "$faculty",
average: {
$avg: "$score"
}
}
}]).exec((err, result) => {
faculties = result;
});
res.render('/scoreboard', {
information: [teams, faculties]
})
Is there a better implementation to handle the queries to run asynchronously?
res.rendersynchronously, before the database calls have returned. To fix this, move theres.renderpart inside the second callback. Better yet, rewrite it so that the two calls to the database run in parallel. Since they're done using callbacks, you could use an npm library calledasyncto combine them. Alternatively, you could wrap them in promises and usePromise.allto combine them.