I have a User model created with mongoose and I'd like the records to either have an email or not. In the case of the user having an email, I'd like it to be unique but in the other case, when the field is null, it will not be unique as multiple user could decide to not provide an email. Is there a way to allow duplicates that have null
values but reject any other duplicate?
I currently have a User schema with an email field as shown here:
const user_schema = new mongoose.Schema({
email: {
type: String,
unique: true,
default: null,
sparse: true
}
})
When doing this, I'm getting the following error: E11000 duplicate key error collection: db.users index: email_1 dup key: { email: null }
I even tried creating an index like this:
user_schema.index({ email: 1 }, { unique: true, sparse: true })
and
user_shema.index(
{ email: 1 },
{ unique: true, partialFilterExpression: { email: { $exists: true } } }
)