Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose/MongoDB throwing duplicate key error on save?

Tags:

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?

like image 464
Abe Miessler Avatar asked Apr 06 '15 16:04

Abe Miessler


People also ask

How do I fix duplicate key errors?

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.

How do I avoid duplicate errors in MongoDB?

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.

Can I use MongoDB and Mongoose at the same time?

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.


1 Answers

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) { /* ... */ }) }); 
like image 103
victorkt Avatar answered Oct 28 '22 18:10

victorkt