Search code examples
node.jsmongodbnode-mongodb-native

Pull object from an array with node-mongodb-native


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?


Solution

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