Mongoose – caused by :: 11000 E11000 duplicate key error index?

You initially had a field called name in your schema, that was set to unique.

How do I know? Because of the error telling me so:

duplicate key error index: **iotdb.users.$name_1**

You renamed the field to username, but didn’t remove the old index. By default, MongoDB will set the value of a non-existent field to null in that case.

Relevant documentation here:

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.

To solve this, you need to remove the index for the renamed name field.

Leave a Comment