在 collection 中查找与 ID 数组匹配的文档

finding documents in a collection that match an array of ids

所以,我在 MongoDB 中有一个名为 cart 的 collection。购物车中的所有文档都有一个字段 cartItems,一个动态数组,其中包含 productID s。我想查询 cartItems 并使用它在另一个名为 Products 的 collection 中找到匹配的 productID,其中包含我拥有的所有产品的详细信息。

这是 collection cart.

文档中的 cartItems 字段
 "cartItems" : [ 
    {
        "productID" : "64ac60de872e",
        "quantity" : 5
    }, 
    {
        "productID" : "13528471cb73",
        "quantity" : 5
    }, 
    {
        "productID" : "e64ac60de8732",
        "quantity" : 5
    }
]

这是 Products 中的文档,其中包含 productID = "64ac60de872e"

产品的一些详细信息
{
   "_id" : ObjectId("64ac60de872e"),
   "Name" : "something",
   "Category" : "cat1",
}

这是我到目前为止在 Meteor 中使用辅助函数尝试做的事情。

  Template.cart.helpers({
   carts: function () {  
   var user = cart.find().fetch()[0];
   var id=[];
   for(i=0;i<user.cartItems.length; i++) {
    id.push(new Mongo.ObjectID(user.cartItems[i].productID));
    console.log(id[i]);
   }
   return Products.find({"_id": { $all :id}});
  }

我在打印 NameCategory 的 html 文件中调用这个助手,但这不是在职的。

如果我这样做

 return Products.find({"_id": id[i]}) 

其中 i=0,1,2 它工作并打印该特定元素的详细信息

如果有人告诉我哪里出错了,我将不胜感激。我觉得我让这件事变得非常复杂,并且有一个更简单的解决方案。

在 mongo 中 $all 等同于 $and,因此要匹配您需要一个包含每个值的 _id 数组的记录。

你想要的是$in,它只需要匹配数组中的一个值。

这是我的做法。我还整理了其他一些东西并添加了评论以说明原因:

  Template.cart.helpers({
   carts: function () {  
   // `findOne` will also return the first result
   var user = cart.findOne();
   // Map creates a new array from the result of running the supplied
   // function over every record
   var id = user.cartItems.map(item => new Mongo.ObjectId(item.productId));
   return Products.find({ "_id": { $in: id } });
  }