mongoose: 11000 E11000 duplicate key error index: dbName.users.$_id_ dup key: { : ObjectId('5469eb08370fea375383e2d3')}
I am trying to save an an array of objects into a db using db.collection.insert
but I am getting this error:
{"code":11000,"index":93,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: dbName.users.$_id_ dup key: { : ObjectId('5469eb08370fea375383e2d3') }
I’ve tried dropping the database and reinserting but of no use. Also, no document with such id is present in the collection earlier.
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Reactions: 5
- Comments: 53
Are you sure you’re dropping the right database? Make sure you do
use dbName; db.dropDatabase();
.Also, can you provide me the insert operation you’re trying to run?
I fixed the E11000 duplicate key error indexes with: new Schema({…}, { autoIndex: false });
When your application starts up, Mongoose automatically calls createIndex for each defined index in your schema. Mongoose will call createIndex for each index sequentially, and emit an ‘index’ event on the model when all the createIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option autoIndex to false.
mongoose.connect(‘mongodb://user:pass@localhost:port/database’, { autoIndex: false }); // or mongoose.createConnection(‘mongodb://user:pass@localhost:port/database’, { autoIndex: false }); // or animalSchema.set(‘autoIndex’, false); // or new Schema({…}, { autoIndex: false });
Sharing my experience:
changed
to
When executed on documents without property “ativo”, error “E11000” was shown. Guess it didn’t found that document and since it is an upsert tryed to insert a new one, but that ID already existed. Updating documents with “ativo” missing solved the problem.
PS: no mongoose, only mongo driver
Thank you so much @skinnn. I have been working on a database reset script for the last day and nothing I tried was working. Randomly got the
dup key
issue. You just saved me more time wasted on this issue.Edit: Oh, correction. Still getting a
dup key
. It seems usingnodemon reset-database.js
to restart the script causes thedup key
error more often than usingnode reset-database.js
.Thanks @skinnn
Ok so turns out that the index on
_id
is always unique and can’t be removed. Whenever a new collection is created, this index is automatically created. Since you’re trying to insert an object with a duplicate_id
, this is expected unfortunately. If you don’t care about_id
, you can explicitly dodelete user._id
before inserting and MongoDB will create a unique_id
for you. If you’re concerned about keeping your_id
’s, then you should figure out why one of them isn’t unique.