I am fetching several ids from the array field stored in mongodb database and I am storing those values into some constant variable as an array.Now I am using map function to iterate through array and based on those ids I am performing some query operation inside map function and when I am getting the result I am storing it inside new array and then I am trying to return that new array to the users.
Below is my code:
const data = await userSchema.findOne({_id:objectId,active:true});
const hubIdArray = data.hubs; //Here storing all the ids getting from db array field
const hubs = []; //Storing values here after performing query opseration inside map function
hubIdArray.map(async (hubId) => {
const hub = await hub_schema.findOne({id:hubId});
hubs.push(hub);
console.log(hubs); // Here I am getting the hubs array.
})
console.log('Out',hubs); // But here its returning an empty array
return res.send(hubs);
Why I am getting the array inside map function but not outside the map function even if I have declared an empty hubs array outside the map function.Someone let me know.
CodePudding user response:
Your map
function is async
so basically your console.log('Out',hubs)
runs before your retrieval was completed.
The easiest way to solve this is to change the map
to a standard for
loop.
const hubs = [];
for (let i = 0; i < hubIdArray.length; i ) {
const hub = await hub_schema.findOne({id:hubIdArray[i]});
hubs.push(hub);
console.log(hubs);
}
console.log('Out',hubs);
return res.send(hubs);