The problem is your Restaurant.findById
line. The function seems to be asynchronous; _.map
is synchronous.
So, when your return your data, it's late. The iteration made by _.map
is probably already finished.
For asynchronous stuff like you want, maybe you should consider using async (async.map),
Example using async:
async.map(branches, function (branch, callback) {
Restaurant.findById(branch._restaurantId, function (err, restaurant) {
callback(null, { restaurant: restaurant, branch: branch });
});
}, function (err, results) {
res.send(results);
});