[英]Find if username and email exist in MongoDB
我试图重写代码,以在创建新用户之前检查MongoDB中是否已经存在用户名和电子邮件。 现在,我的代码在创建新用户之前检查电子邮件是否存在。 它可以工作,但是我很难找到一种添加代码的方式来查看用户名是否也存在
我已经尝试过下面的代码,但它只会为电子邮件返回错误,而不会为用户名返回错误。
User.find({
$or: [{ email: req.body.email }, { username: req.body.username }]
}).then(user => {
if (user) {
if (User.findOne({ email: req.body.email })) {
errors.email = "Email already exists";
return res.status(400).json(errors);
}
if (User.findOne({ username: req.body.username })) {
errors.username = "Username already exists";
return res.status(400).json(errors);
}
} else {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
我的代码仅用于检查电子邮件是否存在:
User.findOne({ email: req.body.email }).then(user => {
if (user) {
errors.email = "Email already exists";
return res.status(400).json(errors);
} else {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
我需要代码来检查用户名是否存在以及返回和错误。 然后检查电子邮件是否存在并返回错误。 然后创建新用户(如果都不存在)
您所做的查询是正确的,您所要做的只是检查什么条件正在返回您的用户。 相同的代码是:
User.findOne({
$or: [{
email: req.body.email
}, {
username: req.body.username
}]
}).then(user => {
if (user) {
let errors = {};
if (user.username === req.body.username) {
errors.username = "User Name already exists";
} else {
errors.email = "Email already exists";
}
return res.status(400).json(errors);
} else {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
})
.catch(err => {
return res.status(500).json({
error: err
});
});
希望这可以帮助 :)
export const myCoolEndPoint = async (req, res) => {
try {
const {username="", email=""} = req.body;
const exists = await User.find({email: email});
if (exists === null) {
return res.status(404).send({message: "User Not found"});
}
if (exists.username !== username) {
return res.status(404).send({message: "NOt found"});
}
return bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(exists.password, salt, (err, hash) => {
if (err) throw err;
exists.password = hash;
const saved = await newUser.save();
// 202 means created
return res.status(202).send({message: "User created"})
});
});
} catch (error) {
res.status(500).send({message: "you broke me </3"});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.