Reputation: 23
UserSchema.path('email').validate(async(email)=>{
const emailcount = await mongoose.models.User.countDocuments({email})
return !emailcount
}, 'Email already exits')
May this help ur question... worked for me.. use in user model. refer for explaination THANKS...
Upvotes: 2
Views: 451
Reputation: 157
First of all from database end, you'll need to add unique constraint to email column. You may check this link for better explanation: Mongoose: How to prevent mongodb to save duplicate email records in database
When you add unique index to a database table column, inserting same value for multiple times will product this error. You can check this error to show custom error message to the user. this link might help you: https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field
Upvotes: 0