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?
There are the following options for handling duplicate key errors: You can delete the file, for example if you know that there are values in the file that are not correct. You can then adjust the file and upload it again. The system will not transfer any data from files that contain duplicate instances.
If you ever faced this error all you need to do is to check your model carefully and find out that is there any unique key set true by you and if it is not necessary then simply remove the unique key from the model or otherwise set a unique value if it is necessary to be unique.
Connecting to MongoDBMongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose. connect() , as shown below. You can get the default Connection object with mongoose.
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) { /* ... */ }) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With