1

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 } } }
)
Blou
  • 191
  • 1
  • 9
  • Null is still a value and cannot be duplicated if the field is unique. You can add a unique value like (uuid)@noemail if user has not provided email. – att Jan 02 '21 at 18:57
  • 1
    Thank you for your answer but what if the field can not have a random value and has to be null? Also I forgot to mention that the uniqueness of the email field depends on the type of account the user decides to choose. The type fiels is an enum field . Would it be possible to determine the uniqueness of the email field based on the value of that other field – Blou Jan 02 '21 at 19:07
  • You have to make a choice between uniqueness and null value. Can’t have both. For different types you may have different mongoose model. – att Jan 02 '21 at 20:04
  • You should specify the email as required and check its uniqueness or do not have these options at all. You can set up the default emails if user did not provide the email, but forget about its uniqueness – Карина Баринова Jan 02 '21 at 20:43
  • You can check [this](https://stackoverflow.com/questions/47407385/mongoose-set-default-to-null-and-unique) answer, I think it will do – Mariano Dec 08 '21 at 20:13

0 Answers0