I have a Schema
var UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: "{VALUE} is not a valid email"
}
}
}
And as you see, email has property "unique". However, when I create a multiple users with the same email there is no errors popping anywhere. So, I decided to create a loop, in "PRE" method. Before I save new user, it checks if the email already exist in mongo then deletes it
UserSchema.pre('save', function (next) {
var user = this;
User.find({email: user.email}).then((res) => {
return User.remove({email: res[1].email});
}).then((res) => {
console.log(res);
next()
});
});
But it deletes every user in collection, even the unique one created before. Can anybody give an advice or tell possible ways of fixing it? Any help appreciated. Maybe there is another way to check email "uniqueness"?