Oliver Nassar

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar


MongoDB in nodejs and the update/upsert command

View more posts

So I ran into a weird issue, which in hindsight makes perfect sense. While trying to issue an "upsert" command (which is apparently similar to a REPLACE command in legit-SQL; insert the record if not found, otherwise update it's values/columns appropriately), it was dying. Here's my flow:

// attempt to open connection; run update-crud operation
__open(function(err, db) {
    __getCollection(db, collection, function(collection) {
        collection.update(
            spec,
            obj,
            {
                upsert: true,
                multi: true,
                safe: false
            },
            callback || function(){}
        );
    });
});

This code follows the following flow:

Seems legit. It all follows the docs a'la the node-mongodb-native package on github. After testing, I found the problem was that I was specifying multi: true.

In hindsight, it makes sense. In the above logic, I was writing out that if a matching "record" was found, update it. I was hoping that if one wasn't found, it should insert it. But how would multi: true work? This flag can only be specified when upsert is set to false. Otherwise, it wouldn't know how many "records" to insert.

Hopefully this saves someone else a little bit of time.