I am using MongoDB and Express JS to develop APIs and I want to run MongoDB query inside foreach loop and then save all data into an array and then use that array somewhere in response but i am not able to access query result outside the foreach loop. Please Help!
My Code:
BucketList.find({ shared_with: req.userId }, function (err, sharedData) {
if (err) {
return res.status(500).send({ message: err, isError: "Y" });
}
if (sharedData.length > 0) {
sharedData.forEach(function (arrayItem) {
sharedArray = arrayItem.shared_with;
var userNameArr = [];
sharedArray.forEach(function (eachUserId) {
User.find({ user_id: eachUserId}, function (err, eachUserData){ //Find all bucket shared with this user
console.log(eachUserData[0].full_name) //Getting Expected Full Name
userNameArr.push(eachUserData[0].full_name) //Storing Full Name instead of userId
});
});
console.log(userNameArr) // Getting Empty Array []
var bucketListData = {
id: arrayItem._id,
bucketName: arrayItem.name,
type: arrayItem.type,
createdOn: arrayItem.created_on,
sharedWith: userNameArr, // I want to user Full Names of the user instead of user Id
};
shared.push(bucketListData);
});
}
var finalList = {
personalBucket: [],
sharedBucked: shared,
};
return res
.status(200)
.send({ message: "Success", isError: "N", bucketList: finalList });
});
use Promise.all like this
var userNameArr = [];
var promiseArr = []
sharedArray.forEach(function (eachUserId) {
promiseArr.push(User.find({ user_id: eachUserId}))
});
Promise.all(promiseArr)
.then(results=>{
results.forEach(item=>{
userNameArr.push(item.full_name)
})
console.log(userNameArr)
})
or use this and do in mongodb
User.find({ user_id:{$in:sharedArray }}).select('full_name').then(r=>{
console.log(r) // it must be as "userNameArr"
})