Tips for “MongoServerError: Plan executor error during findAndModify :: caused by :: E11000 duplicate key error collection“.

Mongo duplicate when findAndModify(), same for findOneAndUpdate()

Don’t try to query the dynamic field with the upsert option!

The same problem will occur when querying multiple conditions (include some not unique fields), while turn on option upsert=true. This results in you querying with “null” results (when a non-unique field has changed), and then upsert is fired. But it is conflicted due to the unique fields that protect the database.

If you still decide to use the findAndModify() query in combination with the “upsert” option. Use try-catche to find a way to handle this special case.

await MyModel.findOneAndUpdate({ uniqueField: "abc", nonUniqueField: 0 }, { $set: { uniqueField: "abc", nonUniqueField: 1 } }, { upsert: true }).catche(error => {
  console.log("nonUniqueField = 2, so I query value 0. This result is null. But I try to insert by upsert option. Throw error by uniqueField")
// Do something for this case
})

Mongo duplicate when use insertMany()

When you insert a document list, one or more documents in your list already exist. So “E11000 duplicate” error is thrown.

In this case, the method simply doesn’t care about some already existing documents. Try to insert a new document in your list into the database. The “ordered=true” option is necessary to solve the problem.

var myList = [{name:"a"}, {name:"b"}]; // name is unique
await MyModel.insertMany(myList, { ordered: false }).then(result => {
  console.log("All documents be inserted")
}).catch(error => {
  console.log("Some documents be inserted")
  console.log(error)
})

,

DMCA.com Protection Status


Leave a Reply

Your email address will not be published. Required fields are marked *