I currently have a specific collection that stores IDs referencing objects in a separate schema.
If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object?
Although I've made an attempt, my results are returning empty objects:
// This code fetches an array of itemIds previously bought by a particular buyer.
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 }); // Current output: "{}, {}, {}, etc"
How can I resolve this issue and ensure that the objects fetched include both the image and name of the items as specified in the select
? Your help is greatly appreciated!