处理Mongo DB的重复电子邮件错误

发布于 2025-02-07 05:29:34 字数 884 浏览 0 评论 0原文

当用户输入已经使用的电子邮件时,我正在尝试犯一个自定义错误。

这是我的寄存器突变:

 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,
  };
},

这是mongo默认错误:e11000重复的密钥错误集合:test.users索引:email_1 dup键:{电子邮件:

我尝试访问此错误而没有成功,如果我知道如何访问此错误,要容易,所以我需要一些提示:) ty

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你曾走过我的故事 2025-02-14 05:29:34

检查是否有该电子邮件的用户,那么,如果您像使用用户名一样,只需丢下错误即可。

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

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"); 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文