简体   繁体   中英

finding documents in a collection that match an array of ids

So, I have a collection in MongoDB named cart . All documents in cart have a field cartItems , a dynamic array, which contains productID s . 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.

Here's the cartItems field in a document of collection cart .

 "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"

{
   "_id" : ObjectId("64ac60de872e"),
   "Name" : "something",
   "Category" : "cat1",
}

Here's what I've tried doing so far using a helper function in 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.

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'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.

What you want is $in , where it just needs to match one of the values in the array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM