所以基本上我有一個集合,其中包含參考另一個模式中的物件的 id。
如果我有一個包含這些 id 的陣列,我如何映射陣列并獲取與該 id 關聯的物件?
到目前為止,這是我所擁有的,但回應只是空物件:
// 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"
我該如何解決這個問題,以便物件包含我在select. 謝謝!
uj5u.com熱心網友回復:
您可以嘗試在陣列中收集專案 ID 并使用$in運算子通過單個查找查詢選擇所有專案,
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326524.html
標籤:javascript 打字稿 MongoDB 表达
上一篇:作為函式引數的擴展介面實作
