Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to return array values after being added into the array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading