Home > database >  Handling duplicate email error from mongo DB
Handling duplicate email error from mongo DB

Time:06-14

I am trying to make a custom error when user is entering email that is already in use.

this is my register mutation:

 register: async (
  _,
  { registerInput: { username, email, password, confirmedPassword } }
) => {
  const { valid, errors } = registerInputValidator(
    username,
    email,
    password,
    confirmedPassword
  );
  if (!valid) {
    throw new UserInputError('Errors', { errors });
  }
  const existUser = await User.findOne({ username });
  if (existUser) {
    throw new UserInputError('User is already exist', {
      errors: {
        username: 'This user is already exist',
      },
    });
  }
  const newUser = new User({
    username,
    email,
    password,
  });
  const res = await newUser.save();

  return {
    ...res._doc,
    id: res._id,
    token,
  };
},

this is mongo default error: E11000 duplicate key error collection: test.users index: email_1 dup key: { email:

I tried to access this error with no success, If I knew how to access this error it would be easy so I need some hints :) ty

CodePudding user response:

Check if there is a user with that email, then if true just throw an error, as you are doing with the username.

const doesEmailExist = await User.findOne({ email });
if (doesEmailExist) {
   throw new Error("Email already exists"); 
}
  • Related