InsertMany throw E11000 duplicate key error but insert successfully

Viewed 6181

I am using mongoose to insert bulk data to database. The insertMany throw E11000 duplicate key error although the data is saved succeed in database.

Here is my codes:

  var data = [
      {_id: '598d7ae7c3148a6d853866e8'}, 
      {_id: '598d7afdc3148a6d853866f4'}
    ]
Movies.insertMany(data, function(error, docs) {});

This happen infrequently.

Appreciated any help.

Thanks

4 Answers

I'm going to add this here for anyone who comes across this issue. I had the same exact issue and the reason I was getting this duplicate key error was because my old mongoose model used to enforce a UNIQUE constraint on one of my keys AND when I removed these unique constraints from my mongoose Model, I forgot to completely remove ALL existing indexes from the database. When I ran: db.mycollection.getIndexes(), I found that the old unique indexes were STILL in my database EVEN after removing all documents from each collection.

To get rid of these indexes I ran: db.mycollection.dropIndexes() in the shell.

Another tip I have for you: If you have a database seeding script that clears your collections & inserts fresh data (e.g for your test suite), I recommend you drop all indexes for each collection AFTER clearing your database. You can drop indexes for your models in mongoose like so: myMongooseModel.collection.dropIndexes()

You should declare a function to find and update, and iterate the array data

set upset and new with true

  _storeLive(data) {
    shemaLive.findOneAndUpdate({
      _id: data._id
    }, data, {
      upsert: true,
      new: true
    }, (err, event) => {
      if (err) {} else {}
    });
  }


customArray.forEach(obj => _storeLive(obj));
Related