Following is my user
schema in user.js
model -
var userSchema = new mongoose.Schema({
local: {
name: { type: String },
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.
The relevant documentation for this:
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. 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.
unique indexes
Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.
In other words, a sparse index is ok with multiple documents all having null
values.
sparse indexes
From comments:
Your error says that the key is named mydb.users.$email_1
which makes me suspect that you have an index on both users.email
and users.local.email
(The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes()
if this is the case and manually remove the unwanted index with mydb.users.dropIndex(
.