1

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that running with this for loop will run the findOnes one after another, and not in parallel as your example did. If you need to run this in parallel then you can change back to map and collect all the promises and await to promise.all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.