【问题标题】:How to check if Email exists , throw error if so , and create user if no match with Sequelize and Express?如何检查电子邮件是否存在,如果存在则抛出错误,如果与 Sequelize 和 Express 不匹配则创建用户?
【发布时间】:2022-02-07 13:13:10
【问题描述】:

我正在尝试检查 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;

【问题讨论】:

  • 这只是抛出电子邮件已经存在但如果我修改电子邮件不再创建,在终端中显示为选择查询而不是现在插入?谁能帮帮我

标签: node.js express sequelize.js


【解决方案1】:

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

if (found != "") 

到下一行:

if (found)

【讨论】:

    【解决方案2】:

    您可以使用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);
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2011-05-12
      相关资源
      最近更新 更多