node.js - Node JS - 使用 findOneAndUpdate 和 Bcrypt 更新密码
问题描述
我是 Node.js 的新手,我正在尝试更新个人资料页面,以便用户可以输入旧通行证和新通行证,并在 DB 中更新
我正在使用findOneAndUpdate
并试图想出一种方法:
1 找到用户
2 获取用户通行证
3 比较旧的 pass 和 DB 中的 pass
4 散列新的通行证
5 更新用户
我想不出findOneAndUpdate
任何办法来做到这一点?
exports.updateUser = (req, res) => {
const {id, username, email, oldPassword, newPassword} = req.body
const v = new Validator()
const schema = {
username: { type: "string" },
email: { type: "email" },
}
const errors = v.validate({ username, email }, schema)
if (errors.length) {
return res.status(400).json({ errors })
}
if (!oldPassword && !newPassword) {
const filter = { _id: id }
const update = { username, email}
userModel.findOneAndUpdate(filter, update, {new: true})
.then( user => {
if (user) {
res.json({message: "User is updated."})
} else {
res.status(400).json({error: "Failed to update user."})
}
})
} else if (oldPassword && newPassword) { // this is the part I can't make
const filter = { _id: id }
const update = { username, email, oldPassword, newPassword}
userModel.findOneAndUpdate(filter, update, {new: true})
// here I need to check if the old pass is good first, then update it with the new hashed pass
.then( user => {
if (user) {
res.json({message: "User is updated."})
} else {
res.status(400).json({error: "Failed to update user."})
}
})
}
}
解决方案
findOneAndUpdate
无法单独完成您正在寻找的事情。它只会找到一条记录并立即更新它——您不能对记录的当前内容进行任何形式的检查。
您需要按照 a 的方式执行某些操作findOne
来检索当前用户记录,检查数据库中的密码是否与新密码匹配,然后使用findOneAndUpdate
它来更新密码是否符合您的条件。
另外,请允许我添加一个强制性提醒,永远不要将用户的密码明文存储在数据库中。您应该查找密码哈希最佳实践并实施这些实践,但这超出了此问题/答案的范围。
推荐阅读
- c++ - 这个大 O 表示法对于这个 c++ 代码是否正确?
- c++ - 在尝试运行这个简单的代码后,我只能输入一次值,为什么?
- c# - CollectionView 抛出 InvalidCastException 或 ObservableCollection 为空
- python - Raspberry Pi 上的 GPIO 引脚状态更改后,如何在 pygame 中更新我的显示?
- python-3.x - 如何更改散点图中两个不同列之间的颜色?
- java - 多线程快速排序比Java中的普通快速排序慢?
- javascript - 选择时无法显示`DragBox`
- api - Golang:响应结构具有多种可能的字段类型
- discord - 命令引发异常:TypeError: get_cog() 接受 2 个位置参数,但给出了 3 个
- python - 根据 Python 中的参数确定要导入的兼容包(带继承)