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

Most upvoted comments

var aladdinId;
    //добавление аладина
    db.collection('Aladdins').insertOne({
      "hash" :  totalAmounts.terminals,
      "public_key_1" :  totalAmounts.terminals,
      "test" : true,
      "created" : 1446296623,
      "updated" : 1446296623,
      "terminal": {"uid": ObjectId(terminalUid)}
      }, function(err, result) {
        assert.equal(err, null);
        aladdinId = result.insertedId;
        var hostId;
        //добавление хоста
        db.collection('Hosts').insertOne({
          "type1" : "ssh",
          "port_counter" : 7108,
          "host": "update1.fet.ru"
          }, function(err, result) {
            assert.equal(err, null);
            hostId = result.insertedId;
            //обновление терминала
            db.collection('Terminals').update(
                {'_id': terminalUid},
                {'$set':
                  {
                    'aladdin':{'uid': ObjectId(aladdinId), 'hash':  "887209212797234849"},
                    'host': {'host': 'update1.fet.ru', 'uid': ObjectId(hostId), 'port': 7108}
                  }
                }, function(err, result) {
                  callback(null, db, totalAmounts, insertedClient);
                }
            );
        });
    });
  });
};
 An error occurred while running the tests:
AssertionError: {"name":"MongoError","message":"E11000 duplicate key error collection: loto_test_soper.Aladdins index: public_key_1 dup key: { : == null
    at /home/severin/projects/NightwatchTests/js/database/insertions.js:436:16
    at /home/severin/projects/NightwatchTests/node_modules/mongodb/lib/collection.js:404:32
    at handleCallback (/home/severin/projects/NightwatchTests/node_modules/mongodb/lib/utils.js:96:12)
    at /home/severin/projects/NightwatchTests/node_modules/mongodb/lib/collection.js:685:42
    at commandCallback (/home/severin/projects/NightwatchTests/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:936:9)
    at Callbacks.emit (/home/severin/projects/NightwatchTests/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:116:3)
    at null.messageHandler (/home/severin/projects/NightwatchTests/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:282:23)
    at Socket.<anonymous> (/home/severin/projects/NightwatchTests/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:273:22)
    at Socket.EventEmitter.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:746:14)

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

BD.collection(collection).updateOne({
        _id: ObjectId(id)
      }, ...
      { upsert: true }

to

BD.collection(collection).updateOne({
        _id: ObjectId(id),
        ativo: true
      }, ...
      { upsert: true }

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 using nodemon reset-database.js to restart the script causes the dup key error more often than using node 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 do delete 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.