store multipule mongoose queries result in one array
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 errorconst req = { body: { offered: [ 'foo', 'bar', ], },};// Used to simulate the async functionconst item = { findById: ([d]) => new Promise((r) => setTimeout(() => r(`Response :: ${d}`), 100)),};// Used for the snippet to run without errorconst 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, });})();