Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Unable to access Array data outside MONGODB query in express JS

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 });
  });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"
   })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!