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

85
Visualizações
store multipule mongoose queries result in one array

I would like to ask your help , I am trying to search my mongoldb data using many ids via axios request ,

I initiate a request with all the ids to node as following

 var data=new FormData()
   data.append("offered",offered)
  axios ({
    url:`http://localhost:5000/items/itemsDetail`,
    method:"POST",
    data:{offered:offered},

   })  

Then in the back end Node model,I initiate the queries as following

 var offered=req.body.offered

  var responsed=[]

  offered.forEach(offer=>{
     item.findById([offer])
      .then(result=>{
       console.log(result)
      responsed.push(result)
     })

     res.json({result:response})

individually it works and it logs the individual result("console.log(result)") , but when I try to collect them and send the ["responsed" variable array] back as a one time response, I got an empty object in the axios respond?!

hope you got my point !

I want to send multi queries and got them once .

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The problem is that item.findById is an asynchronous function.

In order to return all the data, you need to wait for every item.findById to finish.

Look at the following example :

// Used for the snippet to run without error
const req = {
  body: {
    offered: [
      'foo',
      'bar',
    ],
  },
};

// Used to simulate the async function
const item = {
  findById: ([d]) => new Promise((r) => setTimeout(() => r(`Response :: ${d}`), 100)),
};

// Used for the snippet to run without error
const offered = req.body.offered;

// Syntax used to be able to use async/await syntax
(async() =>  {

  // Call every findById and wait for them to finish
  const response = await Promise.all(offered.map(offer => item.findById([offer])));

  console.log({
    result: response,
  });

})();

over 4 years ago · Santiago Trujillo 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