Reputation: 197
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)
Upvotes: 1
Views: 335
Reputation: 3431
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
.
Upvotes: 1