The return signature of findOneAndUpdate()
in the callback is the err
and the document
that was either modified or inserted. There is also a default case that the document returned is the "modified" document unless you set the argument to false
.
Looking an an example case:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = require('mongodb').ObjectID;
mongoose.connect('mongodb://localhost/test');
var uptestSchema = new Schema({
value: Number
});
var Uptest = mongoose.model( "uptest", uptestSchema, "uptest" );
var id = new ObjectId("538c1fea6369faeced1b7bfb");
console.log( id )
Uptest.findOneAndUpdate(
{ _id: id },
{ "$setOnInsert": { value: 3 } },
{ upsert: true, new: false },
function(err, doc) {
console.log( doc );
}
);
Now if the document for the given _id
existed then I would expect to see the "original" document without modifications returned. There is only $setOnInsert
in there anyway so there would be no change.
If however an "upsert" occurred the return value for the "original" document would be null
since there was no document originally. This is what tells you the operation resulted in an "upsert" and created a new document.