如何检查电子邮件是否存在,如果存在则抛出错误,如果与 Sequelize 和 Express 不匹配则创建用户?

How to check if Email exists , throw error if so , and create user if no match with Sequelize and Express?

我正在尝试检查 req.body.email 是否已经存在于 db,然后我想抛出错误,如果不在 db 中,则尝试创建我的用户...但这失败了它唯一返回的电子邮件在系统中,即使我更改了电子邮件,任何人都可以帮助我解决这个问题吗?

const User = require("../models/users");

const createSingleUser = async (req, res) => {
  // we need to make sure the provided email is not being used if it exists in the db
  // them we through an error if not then we create the user
  // step one lets search by the email provided
  const checkEmail = req.body.email;
  const found = await User.findOne({
    where: {
      email: checkEmail,
    },
  });
  // if found is not empty meaning a match was found
  if (found != "") {
    res.send("this email is already in system");
  } else {
    // create the user since its empty no match found
    try {
      const newUser = await User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        dateOfBirth: req.body.dateOfBirth,
        email: req.body.email,
        phone: req.body.phone,
      });
      User.sync({ alter: true });
      res.send(await newUser);
    } catch (err) {
      res.send(err);
    }
  }
};

module.exports = createSingleUser;

您还应该向我们提供 found 包含的内容的日志,但猜测可能会尝试更改此行:

if (found != "") 

到下面一行:

if (found)

您可以使用findOrCreate

const createSingleUser = async (req, res) => {
  const { email } = req.body;
  const [user, created] = await User.findOrCreate({
    where: { email },
    defaults: { ...req.body }
  });
 
  if (!created) {
    res.send("this email is already in system");
  } 
  return res.send(user);
};