Reputation: 3560
I am unable to call mongoDB callback function inside the loop. I am providing my array and code below.
[
{
"location": "NEW DELHI",
"nos_of_fos": 15,
"login_id": [
"9619300317",
"9619300343",
"9619300338",
"9619300351",
"9619300322",
"9619300316",
"9619300323",
"9619300328",
"9619300341",
"9619300309",
"9619300310",
"9619300329",
"9619300353",
"9619300356",
"[email protected]"
],
},
{
"location": "North West Delhi",
"nos_of_fos": 6,
"login_id": [
"9619300355"
],
}
]
The above is my input array.
finalOut.forEach(function(listItem, index){
var remarkCount=0;
console.log('items',listItem['login_id']);
listItem['login_id'].forEach(function(item, index1){
Feedback.collection.countDocuments({login_id:item},function(cerr,cdocs){
if (!err) {
if (docs >0) {
console.log('docsinner',cdocs);
remarkCount+=parseInt(cdocs);
}
}
})
})
console.log('docsout',remarkCount);
finalOut[index]['total_remarks']=remarkCount;
})
Here before finishing mongoDB checking for first iteration loop getting finished. Here I need to check one by one login_id value and only after finishing the mongoDB task new count will assign.
Upvotes: 0
Views: 32
Reputation: 278
finalOut.forEach(function(listItem, index) {
var remarkCount = 0;
var promises = listItem['login_id'].map(function(item, index1) {
return new Promise((resolve, reject) => {
Feedback.collection.countDocuments({ login_id: item }, function(
err,
docs
) {
if (!err) {
if (docs > 0) {
console.log('docsinner', docs);
remarkCount += parseInt(docs);
}
resolve();
}
reject();
});
});
});
Promise.all(promises)
.then(() => {
finalOut[index]['total_remarks'] = remarkCount;
})
.catch(err => {});
});
Upvotes: 1