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() },
'update' : { $set : {
firstName : this.firstName,
lastName : this.lastName,
email : this.email
}},
'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?