如何检查电子邮件是否存在,如果存在则抛出错误,如果与Sequelize和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);
};

最新更新