'How to apply unique constraints only on specific fields in MongoDB
I have a User schema as follows(JavaScript):-
const userSchema = mongoose.Schema({
name: {
type: String,
required: [true, "User must have a name."]
},
password: {
type: String,
required: [true, "User must have a password."],
minLength: 8,
select: false
},
email: {
type: String,
required: [true, "User must have an email."],
unique: true,
lowercase: true,
validate: [validator.isEmail, "Email should be in correct format."]
},
active: {
type: Boolean,
default: true,
select: false
}
}
I want to make sure that email is unique but only for the documents where active is set to true. Is this even possible or should I make another collection for inactive user?
Thank you.
Solution 1:[1]
This is an anti-pattern, because if a user can suddenly become active after he wasn't active so you will have to enforce a logic to make sure his email is still unique.
I would create a unique index on the email field regarding the active state and only in case you need to keep the non-active users somewhere AND you know a user can't become active again (This is important) so create a new collection for inactive users (keep in mind mongo docs are maximum 16mb so make sure you're not creating an array that can grow without bound)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | asafel |
