Node.js 更新MongoDB文档(在NodeJS中)
我有一个用户文档Node.js 更新MongoDB文档(在NodeJS中),node.js,mongodb,express,Node.js,Mongodb,Express,我有一个用户文档 username: "Ralph", email: "ralph@gmail.com", resetPasswordToken: null, resetPasswordExpires: null 我想更新快速路线中的resetPasswordToken和resetPasswordExpires属性 我这样做: router.post("/forgotPassword", (req, res) => { User.findOne({ email: req.body.e
username: "Ralph",
email: "ralph@gmail.com",
resetPasswordToken: null,
resetPasswordExpires: null
我想更新快速路线中的resetPasswordToken和resetPasswordExpires属性
我这样做:
router.post("/forgotPassword", (req, res) => {
User.findOne({ email: req.body.email }).then(user => {
if (user === null) {
console.log("NO user with this mail exists");
} else {
console.log("user with this mail exists");
const token = crypto.randomBytes(20).toString("hex");
const myDate = new Date();
const newDate = new Date(myDate);
user.update({
resetPasswordToken: token,
resetPasswordExpires: newDate.setHours(newDate.getHours() + 1)
});
我在终端中看到日志“有此邮件的用户存在”,但user.update从未完成,因为我的MongoDB数据库中没有任何更改
有人有解决办法吗?谢谢
仅供参考:.update()已被Mongo弃用。您应该切换到.updateOne()
注意,您需要在模型上调用.updateOne()函数,而不是在返回的承诺上
router.post("/forgotPassword", (req, res) => {
// deconstruct email from form
const { email } = req.body
// check if email is registered in the database
User.findOne({ email })
.then(user => {
if (!user) {
console.log("This email is not associated with a registered account");
// send error message to the client
return res.status(404).json("This email is not associated with a registered account");
}
console.log("This email exists in the database. Proceeding...")
})
.catch(err => {
return res.status(500).json(err.message);
});
const token = crypto.randomBytes(20).toString("hex");
const myDate = new Date();
const newDate = new Date(myDate);
// if the email exists, run this update to the account with the associated email
User.updateOne({ email: "ralph@gmail.com" }, {
$set: {
resetPasswordToken: token,
resetPasswordExpires: newDate.setHours(newDate.getHours() + 1)
}
})
.then(updates => console.log(updates))
.catch(err => {
return res.status(500).json(err.message);
});
});
在这里,我们查询以查找电子邮件所在的文档ralph@gmail.com,并使用$set运算符将resetPasswordToken和resetPasswordExpires的关联值更新为各自的新值。好,但我已经执行了上面的User.findOne,以查看是否有用户使用此邮件,如果有,返回错误消息以便我删除此?不,您不需要删除它。你说你的问题是user.update没有执行,所以我正在解决这个问题。用我的答案替换代码段中的user.update(…)。我尝试了您的解决方案,但它不起作用。但这很奇怪,因为我的服务器中有一个更新,我编辑了我的答案,同时重构了代码并做了一些小的添加。看一看