anishkarthick s
anishkarthick s

Reputation: 23

Prevent mongoDB to save duplicate email

Prevent mongoDB to save duplicate email

 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

Answers (2)

Zahid Hassan Alvi
Zahid Hassan Alvi

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

virtuallylost
virtuallylost

Reputation: 21

Set { unique: true } where you define your schema.

Upvotes: 1

Related Questions