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

84
Views
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 answers
Answer question

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 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!