【问题标题】:How to map an array of objectIDs and get objects with those ids?如何映射 objectID 数组并获取具有这些 id 的对象?
【发布时间】:2021-10-20 03:57:18
【问题描述】:

所以基本上我有一个集合,其中包含引用另一个模式中的对象的 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 中指定的图像和项目名称。谢谢!

【问题讨论】:

    标签: javascript typescript mongodb express


    【解决方案1】:

    您可以尝试在数组中收集项目 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;
    }
    

    【讨论】:

    • 太棒了!奇迹般有效!但是,有没有一种方法可以向查询添加验证,以便如果具有该 itemId 的项目不再存在,它将忽略并且不会终止整个查询?
    • 不在查询中,但我在 asnwer 中添加了条件。
    猜你喜欢
    • 2021-12-04
    • 2019-09-08
    • 1970-01-01
    • 2020-08-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2023-01-13
    相关资源
    最近更新 更多