【问题标题】:finding documents in a collection that match an array of ids在集合中查找与 ID 数组匹配的文档
【发布时间】:2019-01-10 23:25:21
【问题描述】:

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

这是集合 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 它可以工作并打印该特定元素的详细信息

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

【问题讨论】:

  • $all 有什么问题?为什么它不起作用?

标签: javascript mongodb meteor


【解决方案1】:

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

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

我会这样做。我还整理了一些其他的东西并添加了 cmets 来说明原因:

  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 } });
  }

【讨论】:

  • 好吧,所以我实现了您编写的内容并在控制台中打印了 id 变量。我看到它给出了一堆随机的 id,我认为它们是由 map 函数生成的。所以我放了我以前用过的 for 循环,现在它可以工作了。正如你所说,问题在于 $all。 $in 是要走的路。谢谢!
猜你喜欢
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多