store multipule mongoose queries result in one array

Viewed 23

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 .

1 Answers

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,
  });

})();

Related