简体   繁体   中英

Why this partialFilterExpression is throwing an error?

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM