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

时间:2018-08-03 06:15:32

标签: javascript mongodb meteor

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

这是收藏集 cart 中的 cartItems 字段。

 "cartItems" : [ 
    {
        "productID" : "64ac60de872e",
        "quantity" : 5
    }, 
    {
        "productID" : "13528471cb73",
        "quantity" : 5
    }, 
    {
        "productID" : "e64ac60de8732",
        "quantity" : 5
    }
]

这是产品中的文档,其中包含 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}});
  }

我在一个HTML文件中调用此帮助程序,该文件显示名称类别,但这不起作用。

如果我这样做

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

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

如果有人告诉我我要去哪里错了,我将非常感谢。我觉得这让我真的很复杂,并且有一个更简单的解决方案。

1 个答案:

答案 0 :(得分:0)

在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 } });
  }
相关问题