24
votes

According to MongoDB's documentation a call to save will create a new document, or update an existing document if _id is provided. Mongoose's documentation is less detailed and does not go into whether it will insert or update.

I am attempting to use Mongoose's save function to update a document, but I keep getting the error:

{"error":{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: staging.participants.$_id _ dup key: { : ObjectId('5515a34ed65073ec234b5c5f') }"}}

Does Mongoose's save function perform an upsert like MongoDB's save function or is it just performing an insert?

1

1 Answers

30
votes

What defines whether the save will be an insert or an update is the isNew flag, as you can see here.

This flag is set automatically to false when the document instance is returned from a find query (or any of its variations). If you are instantiating the document manually, try setting this flag to false before saving it:

var instance = new Model({ '_id': '...', field: '...' });
instance.isNew = false;
instance.save(function(err) { /* ... */ });

There is also an init function, that will initialize the document and automatically set isNew to false:

var data = { '_id': '...', field: '...' };
var instance = new Model();
instance.init(data, {}, function(err) {
    instance.save(function(err) { /* ... */ })
});