MongoDB findAndModify () adds query to update clause

I am building an application in Node that has some CRUD components. On one of my data objects, I have a method save()that is designed to update a record if the object has an identifier found in the collection, or update a new document if not. Also, if you are doing upsert, I would like to return _id for the document created by Mongo.

It seems that findAndModify will do this, and indeed it returns the _id value from the database. In my query question, I filter _id. If my data object does not have an identifier, Mongo does the upsert correctly, however, no matter what value is returned to it, in addition to the keys that I set in the sentence update, it also sets _id to the document based on what value I used in the sentence query. Some code for clarity:

User.prototype.save = function(callback) {
    var that = this;

    var args = {
        'query'     : { _id: this.getId() }, //getId() returns empty string if not set
        'update'    : { $set : {
            firstName   : this.firstName,
            lastName    : this.lastName,
            email       : this.email
          //_id        : this.getId()
          // which is blank, is magically getting added due to query clause
        }},
        'new'       : true,
        'upsert'    : true,
        'fields'    : {'_id' : true}
    };

    this.db.collection(dbName).findAndModify(args, function(err, doc){
        if(!that.getId()) {
            that.setId(doc._id);
        }

        if (typeof(callback) === "function"){
            callback.call(that);
        }
    }); 
}

I'm just looking for update semantics that also returns Mongo's _id file returned by upsert. I do not want suggestion values ​​to querybe added as if they were on a map update. Is there any way to achieve what I get?

+3
1

_id, new require('mongodb').ObjectID() upsert ( findandmodify), _id.

, findAndModify, , node , (, mongo). findandmodify node :

collection.findAndModify(criteria, sort, update[, options, callback])

( ). : https://github.com/mongodb/node-mongodb-native/blob/master/docs/insert.md

+2

All Articles