I'm calling mongoose query inside of another mongoose query. When I push results to a array, When ever I check it at last it is empty. After seacrching a lot, Found that issue is this executes asynchronously. But can't find how to fix the issue. My code is as follows.
Bus.find().exec(function(err,buses) {
if(err)
console.log(err);
if (buses[0] != null){
const cords = [];
buses.forEach( function (bus) {
// console.log(bus);
Position.findOne({"busId": bus.busId},{}, {sort : {'time' : -1}}, function (err, position) {
cords.push(position);
console.log(cords);
// console.log(position);
});
console.log(cords);
},
function (err) {
if (err){
console.log(err,"Errrrrrrrrrrrrr");
}
});
console.log(cords);
res.json({cords: cords});
}
via HelpingHand
No comments:
Post a Comment