Unique partial index is not working with mongoose on email

I am using mongodb version 4.4.8 and mongoose version 5.5.9. I have an user schema and this is how i define it

let User = new Schema({
    email: { type: String, required: true, unique: true},
    phone: { type: String, required: true, unique: true},
    terms_accepted: { type: Boolean, required: true } 
});

I checked in the mongo compass the unique index was created for email and phone. I restarted the mongodb and reindex it too. I can save the data with same email address. While the phone unique index works fine.

If i use ‘mongoose-unique-validator - version 2.0.6’ plugin, email index works as expected. I want to use partial index with unique constraint in my model. And i tried it like this

email: { type: String, required: true, index: {
    unique: true,
    partialFilterExpression: { terms_accepted: true }
}}

I tested this (with or without mongoose-unique-validator) by setting ‘terms_accepted’ to true and false, email index doesn’t work on saving the data. I tried creating the index manually in compass, it doesn’t work either. I have tried every solution on stack overflow without any success. And i can’t figure out what’s the issue.

2 Likes