I'm trying to loop through this array and append user objects to each object inside. How do I wait for each of them to complete before returning the JSON to the client?
Match.find()
.or([{ user_id: req.user._id }, { second_user_id: req.user._id }])
.exec((err, result) => {
if (err) {
return res.sendStatus(500);
}
result.map(async match => {
match.user = await User.findById(req.user._id).exec();
});
return res.json({ matches: result });
});
In this case the array is returned to the client before Mongoose has a chance to resolve the findById queries.