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

164
Views
How to map an array of objectIDs and get objects with those ids?

So basically I have a collection that holds ids which reference objects in another schema.

If I have an array which holds these ids, how can I map through the array and get the object associated with that id?

This is what I have so far but the response is just empty objects:

// this gives me an array of all the itemIds that a buyer has bought.
const prevPurchases = await Sales.find({ buyerId }).select(["itemId"]);

const item = prevPurchases.map(async (e) => {
   try {
      const item = await Item.findById(e.itemId).select(["image", "name"]);
      return item;
   } catch (e) {
      return null;
   }
});

await Promise.all(item);

return res.status(200).json({ item }); // just returns "{}, {}, {}, etc" 

How can I fix this so that the objects contain the image and the name of item as I specified in the select. Thank you!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can try collecting item ids in array and use $in operator to select all the items by single find query,

try {

  const prevPurchases = await Sales.find({ buyerId }).select(["itemId"]);

  let items = [];
  if (prevPurchases.length) { 
    items = await Item.find({ 
      _id: { $in: prevPurchases.map((e) => e.itemId) } 
    }).select(["image", "name"]);
  }

  return res.status(200).json({ items });

} catch (e) {
  return null;
}
about 4 years ago · Juan Pablo Isaza 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!