3

Doc:

{
    "_id" : ObjectId("5399ba7f8035beb2d4717cc0"),
    "listName" : "firstList",
    "items" : [
        {
            "pName" : "iPad ",
            "pDesc" : "iPad aiiir",
            "ownerID" : ObjectId("5399b596c501732dd4d13923"),
            "_id" : ObjectId("5399e2cc2d7b0349d89d2b44"),
            "dateAdded" : ISODate("2014-06-12T17:26:36.282Z")
        },
        {
            "pName" : "iPhone ",
            "pDesc" : "5s",
            "ownerID" : ObjectId("5399b596c501732dd4d13923"),
            "_id" : ObjectId("5399e2cc2d7b0349d89d2b44"),
            "dateAdded" : ISODate("2014-06-12T17:26:36.282Z")
        }
]}

I want to remove an item from the "array" items without knowing the _id of the document only the id of the element, I have this query that finds the element, it works in mongodb shell but doesn't in mongoose,

db.lists.find( {items:
               {$elemMatch:{'_id':ObjectId("5399b596c501732dd4d13923")}}} , 
               {"items.$":1});

Do you have an idea why ?

Can you please give me the equivalent in mongoose ?

How should I pull the item from the list knowing only its _id ?

Ben
  • 469
  • 2
  • 4
  • 20

2 Answers2

4

This should do the trick:

db.lists.update(
    {}, 
    { $pull: {"items": {"_id" :ObjectId("5399e2cc2d7b0349d89d2b44") }},
    { multi: true }})

For every document in the collection ({} means empty query), it removes every item with the provided _id (in the items array). Without the multi option, only the first document found will be affected

yves amsellem
  • 7,106
  • 5
  • 44
  • 68
1

Ok so I found the mongoose solution to my problem thanks to Yves Amsellem. The mongoose version of his answer is:

    Lists.update(
                 {}, 
                 {$pull: {items: {_id: iProductId}}},  
                 { multi: true },
                 function(err, data){
                      console.log(err, data);
                 }
    );
Ben
  • 469
  • 2
  • 4
  • 20