Home > Blockchain >  How to map an array of objectIDs and get objects with those ids?
How to map an array of objectIDs and get objects with those ids?

Time:10-20

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!

CodePudding user response:

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;
}
  • Related