mongoose unique error message 1

mongoose unique error message

emailVerificationTokenSchema.post('save', function(error, doc, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('email must be unique'));
  } else {
    next(error);
  }
});

Here is what the above code is Doing:
1. We are creating a new schema for the email verification token.
2. We are using the mongoose-unique-validator plugin to validate the uniqueness of the email field.
3. We are using the post save hook to catch the error thrown by the mongoose-unique-validator plugin and throw a custom error.

Similar Posts