Reputation: 18
I am trying to implement a forEach to fetch data from a mongo database and push each data to an array. I need to console log that array after all data is pushed. I tried with a promises but couldn't get desired result. Here's what I've got
count=[];
array.forEach((data)=>{
userDetailsModel.find({UpdateStatusDate:data}).countDocuments()
.exec((err,data)=>{count.push(data)})
})
Thanks for any help!
Upvotes: 0
Views: 545
Reputation: 14904
Make sure your function has async
keyword infront of it and you should be good to go
let count = await Promise.all(
array.map(data =>
userDetailsModel
.find({ UpdateStatusDate: data })
.countDocuments()
.exec()
)
);
consle.log(count);
Upvotes: 1
Reputation: 1066
You are missing the point of the promise pattern applied to an array of promises.
Exec
will return a promise that will resolve only for one element of the data array.
Thus you will have a promise for each data in your array and your code must wait for all promises to resolve. Keep in mind this will result in one Mongo query per data in your array.
Best way to do so is to map your data array to an array of promises and use Promise.all
to wait for all of them to resolve:
// get an array of promises for each data to query:
let promises = array.map(data => {
return userDetailsModel
.find({UpdateStatusDate:data})
.countDocuments()
.exec();
});
// when all the promises fulfill
Promise.all(promises).then(counts => {
console.log(counts);
// for each counts log the result:
counts.forEach(result => { console.log(result); });
});
Upvotes: 1
Reputation: 470
You could use the Promise.all() method to wait after all promises
let count = [];
const promiseArray = array.map((data) => (
new Promise((resolve) => {
userDetailsModel.find({ UpdateStatusDate: data })
.countDocuments()
.exec((err, data) => { resolve(data) })
})
))
Promise.all(promiseArray).then((values) => {
count = values;
console.log(count);
});
Upvotes: 0