Guidelines

How do I resolve E11000 duplicate key error?

How do I resolve E11000 duplicate key error?

You essentially have three options:

  1. Drop the collection. db.users.drop();
  2. Find the document which has that value and delete it. Let’s say the value was null, you can delete it using: db.users.remove({ email_address: null });
  3. Drop the Unique index: db.users.dropIndex(indexName)

What is E11000 duplicate key error collection?

MongoDB’s E11000 error is a common source of confusion. This error occurs when two documents have the same value for a field that’s defined as unique in your Mongoose schema. MongoDB collections always have a unique index on _id , so trying to insert a document with a duplicate id will cause a duplicate key error.

How do I avoid duplicate errors in MongoDB?

In MongoDB, the primary key is reserved for the _id field. This is a system field and gets created by default when inserting new records. When you want to enforce the uniqueness in other fields, you can use unique index.

How do I make a field unique in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

Why do I get duplicate Index error in MongoDB?

If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

How to get rid of duplicate key in MongoDB?

So the mongodb may automatically set the ‘name’ value of new record as null which is duplicate key. I tried the set ‘name’ key as not unique key {name: {unique: false, type: String}} in ‘User’ schema in order to override original setting.

Why is there an error message in MongoDB?

The error message is saying that there’s already a record with null as the email. In other words, you already have a user without an email address. If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document.

Why does MongoDB store null values in unique index?

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field.