[英]finding documents in a collection that match an array of ids
So, I have a collection in MongoDB named cart . 因此,我在MongoDB中有一个名为cart的集合。 All documents in cart have a field cartItems , a dynamic array, which contains productID s .
cart中的所有文档都有一个字段cartItems ,这是一个动态数组,其中包含productID 。 I want to query cartItems and use it to find the matching productIDs in another collection called Products that contains details of all the products I have.
我想查询cartItems并使用它在另一个名为Products的集合中查找匹配的productID,该集合包含我拥有的所有产品的详细信息。
Here's the cartItems field in a document of collection cart . 这是集合cart的文档中的cartItems字段。
"cartItems" : [
{
"productID" : "64ac60de872e",
"quantity" : 5
},
{
"productID" : "13528471cb73",
"quantity" : 5
},
{
"productID" : "e64ac60de8732",
"quantity" : 5
}
]
and here's a document in Products that has some details of product with productID = "64ac60de872e" 这是产品中的文档,其中包含productID =“ 64ac60de872e”的产品的一些详细信息
{
"_id" : ObjectId("64ac60de872e"),
"Name" : "something",
"Category" : "cat1",
}
Here's what I've tried doing so far using a helper function in Meteor. 到目前为止,这是我尝试使用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}});
}
I'm calling this helper in an html file that prints the Name and Category but this isn't working. 我在打印名称和类别的html文件中调用此帮助程序,但这不起作用。
If I do 如果我做
return Products.find({"_id": id[i]})
where i=0,1,2 it works and prints the details of that particular element 当i = 0,1,2时,它将工作并打印该特定元素的详细信息
I'd really appreciate if someone tells me where I'm going wrong. 如果有人告诉我我要去哪里错了,我将不胜感激。 I feel like I'm making this really complicated and there is a simpler solution.
我觉得这让我变得非常复杂,并且有一个更简单的解决方案。
In mongo $all
is equivalent to $and
, so to match you would need a record with an _id
array containing every value. 在mongo中,
$all
等同于$and
,因此要匹配,您将需要一个包含_id
数组且包含每个值的记录。
What you want is $in
, where it just needs to match one of the values in the array. 您想要的是
$in
,它只需要匹配数组中的值之一。
Here's how I would do it. 这就是我要做的。 I've also tidied a couple of other things and added comments for why:
我还整理了其他几件事,并添加了以下原因的评论:
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 } });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.