Estoy usando MongoDB y Express JS para desarrollar API y quiero ejecutar la consulta de MongoDB dentro del bucle foreach y luego guardar todos los datos en una matriz y luego usar esa matriz en algún lugar en respuesta, pero no puedo acceder al resultado de la consulta fuera del bucle foreach. ¡Por favor ayuda!
Mi código:
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 así
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) })o usa esto y hazlo en mongodb
User.find({ user_id:{$in:sharedArray }}).select('full_name').then(r=>{ console.log(r) // it must be as "userNameArr" })