【发布时间】: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}});
}
我在打印 Name 和 Category 的 html 文件中调用此帮助程序,但这不起作用。
如果我这样做了
return Products.find({"_id": id[i]})
其中 i=0,1,2 它可以工作并打印该特定元素的详细信息
如果有人告诉我哪里出错了,我将不胜感激。我觉得我让这变得非常复杂,并且有一个更简单的解决方案。
【问题讨论】:
-
$all 有什么问题?为什么它不起作用?
标签: javascript mongodb meteor