Abhishek Rastogi Abhishek Rastogi - 1 year ago 55
Node.js Question

Remove a single object from an array of objects in a single document of a collection

I have a problem with which I am struggling for quite some time.Suppose my document is like this

{"owner":"princu7", "books":[{"name":"the alchemist"}, {"name":"the alchemist"}, {"name":"the alchemist"}].

Now what do I do if I have to just remove one single element from the books array based on the matching of the name?I did it like this

var bookName="the alchemist";
var obj={"name":bookName}
db.collection("colName").update({"owner":"princu7"}, {$pull:{books:obj}}, {multi:false})

But the problems is that it removes all the entries in the array which have the name matching to "the alchemist". What I wanted was this

{"owner":"princu7", "books":[{"name":"the alchemist"}, {"name":"the alchemist"}

But what I got was this

{"owner":"princu7", "books":[]}

Upon reading the documentation, it says that pull removes all the instances that match the required condition so maybe that's why it's removing all other entries of the array which match the condition.So what should I do here.Thanks for reading.Really appreciate your help.

Answer Source

You could use collection.updateOne() with upsert set to true to re-write the record in place. The idea is you get the original document, modify it in your app logic, then re-apply it to the database after removing the element from the array.

function upsert(collection, query, json) {
    var col = db.collection(collection);
        , { $set : json }
        , { upsert : true }
        , function (err, result) {
            if(err) {
                log('error = ', err);
            } else {
                // no error, call the next function

For the details of removing an element from an array in JavaScript, this post is highly voted: http://stackoverflow.com/a/5767357/1161948

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download