Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda