我有一个Node.js代码示例,它根据电子邮件从数据库中提取用户,进行一些检查,按ID和更新执行findOne,如下所示:
User.findOne({ email }, (err, user) => {
if (err) { return next(err); }
if (!user) {
return res.status(422).send({ error: { message: "User doesnt exists", resend: false } });
}
if (user.auth.used) {
return res.status(422).send({ error: { message: "link already used", resend: false } });
}
if (new Date() > user.auth.expires) {
return res.status(422).send({ error: { message: "link already expired", resend: true } });
}
if (token !== user.auth.token) {
return res.status(422).send({ error: { message: "something has gone wrong, please sign up again", resend: false } });
}
User.findByIdAndUpdate(user.id, { role: 1, auth: { used: true } }, (err) => {
if (err) { return next(err); }
const { email, firstname, lastname } = user;
res.json({ token: tokenForUser(user), email, firstname, lastname });
});
});
我可以不仅仅更新并保存我已经拥有的用户吗?:
Token.findOne({ token: req.body.token }, function (err, token)
{
if (!token || token !== user.auth.token) return res.status(422).send({ error: { message: "Link doesn't exist or has expired", resend: true } });
// If we found a token, find a matching user
User.findOne({ _id: token._userId }, function (err, user)
{
if (!user) return res.status(422).send({ error: { message: "We couldn't find a user for this token", resend: false } });
if (user.isVerified) return res.status(422).send({ error: { message: "link already used", resend: true } });
// Verify and save the user
user.isVerified = true;
user.save(function (err)
{
if (err) { return res.status(500).send({ msg: err.message }); }
res.json({ token: tokenForUser(user), req.user.email, req.user.firstName, req.user.lastName, req.user.company })
});
});
});