Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda