1

I have a User schema like this, when a user registers I want to set the default value as null but also to be able to set this value as unique. I tried the solution from this post I literally copied the same solution however I am still getting this error MongoError: E11000 duplicate key error index: ppp-ng-dev.users.$mobile_1 dup key: { : null }

My Schema

const userSchema = new Schema({
    mobile: {
            type: Number, 
        required: false,
        index: {
            unique: true,
            partialFilterExpression: {mobile: {$exists: true }}
        },
        default: null,
    },
})

Why am I receiving this error even when the syntax is correct? (aparently)

1 Answers1

1

The issue is that there are multiple documents in the collection with the value null for the field mobile. This violates the uniqueness constraint of the specified index. As JohnnyHK noted in the ticket you linked:

Note that a unique, sparse index still does not allow multiple docs with an email field with a value of null, only multiple docs without an email field.

In your specific case, the partialFilterExpression specifies to only index documents where the field mobile exists, which includes documents where the field is defined and explicitly defined as null.

Adam Harrison
  • 3,323
  • 2
  • 17
  • 25
  • Thanks for your reply! So is there a way to allow null values to be saved into `mobile` field while maintaining uniqueness of the field? – Rodrigo Villalobos Apr 11 '19 at 00:54
  • I'm not able to test it right now, but you might want to look into having the partialFilterExpression on `$type` instead of `$exists: true`. This would exclude null values and index only defined values. I'm not sure what underlying BSON type will be used for `Number` in Mongoose though, so you may want to look into that and possibly consider storing as a string instead. – Adam Harrison Apr 11 '19 at 04:53
  • I am getting the same errors, even when no documents have `mobile` explicitly set to null. – Asu Sep 10 '20 at 18:57