0

I have been trying to use the MongoDB findOne method but I don't know how use it. The problem is that I have a shema:

const CartSchema = mongoose.Schema({
    user_id: { type: String },
    products: [{
        prod_id: { type: String },
        qty: { type: Number }
    }]
});

And this is my query:

ShoppingCart.findOne(
    { $and: [
       { user_id: Item.idUser },
       { products: [{ prod_id: Item.idProd }] }  // my problem is here
    ] },
    callback    
);

I need to find this data within the {products} object but and I don't know how to refer to this position

Ian Phill
  • 3
  • 1
  • Also see [Query an Array of Embedded Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/) in the core documentation – Neil Lunn Apr 23 '18 at 00:05

1 Answers1

1

You use $elemMatch for this. For example

   ShoppingCart.findOne(
{ $and: [
   { user_id: Item.idUser },
   { products:  {$elemMatch : {prod_id : "ID"}} }
] },
callback    
);

Read more about it here

Muhammad Usman
  • 9,463
  • 18
  • 35
  • Thank you. You are a genius. It's working now – Ian Phill Apr 22 '18 at 23:26
  • I've added link. You must read about it to have a firm understanding. ps. Consider accepting this answer if this resolved your query – Muhammad Usman Apr 22 '18 at 23:27
  • @IanPhill This is not actually "strictly" correct. For a **single** value to match in an array you can simply use "dot notation" to represent the element `ShoppingCart.findOne({ user_id: Item.idUser, "products.prod_id": "ID" }, ...` The `$elemMatch` operator is for "multiple" conditions, i.e `ShoppingCart.findOne({ user_id: Item.idUser, products: { $elemMatch: { prod_id": "ID", qty: { $gt: 1 } } } }, ...`. Also `$and` is rarely needed, and is basically implied of ALL query conditions. Just so you **both** know. – Neil Lunn Apr 23 '18 at 00:04