0

I'm struggling with a simple operation with the mongodb native driver for nodejs. Here is my mongo document:

{
    "_id" : 1,
    "foo" : "bar",
    "baz" : [
         {
            "a" : "b",
            "c" : 1
         },
         {
            "a" : "b",
            "c" : 2
         }
    ]
}

and I have a var like the following :

var removeIt = {"a" : "b", "c" : 1};

So to pull this object from the baz array I try to do the following :

collection.update(
        {_id:1}, 
        {$pull:{baz:{a:removeIt.a, c:removeIt.c}}},
        {safe:true},
        function(err, result) {}
);

But this doesn't seem to work, and I cannot get why, any idea?

xavier.seignard
  • 11,254
  • 13
  • 51
  • 75

1 Answers1

3

I've just tried this on the MongoShell, and the following works for me:

> db.test.insert( {
    "_id" : 1,
    "foo" : "bar",
    "baz" : [
         {
            "a" : "b",
            "c" : 1
         },
         {
            "a" : "b",
            "c" : 2
         }
    ]
});

> db.test.findOne();
{ "_id" : 1, "baz" : [ { "a" : "b", "c": 1 }, { "a" : "b", "c" : 2 } ], "foo" : "bar" }

> removeIt = {"a" : "b", "c" : 1};
> db.test.update( { _id: 1 }, { $pull: { baz: removeIt } } );

> db.test.findOne();
{ "_id" : 1, "baz" : [ { "a" : "b", "c" : 2 } ], "foo" : "bar" }

So modify your:

{$pull:{baz:{a:removeIt.a, c:removeIt.c}}}

to:

{$pull:{baz: removeIt}}

And it should work.

Derick
  • 35,169
  • 5
  • 76
  • 99