首页 > 解决方案 > 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."})
        }
      })
  }

}

标签: node.jsmongoosebcrypt

解决方案


findOneAndUpdate无法单独完成您正在寻找的事情。它只会找到一条记录并立即更新它——您不能对记录的当前内容进行任何形式的检查。

您需要按照 a 的方式执行某些操作findOne来检索当前用户记录,检查数据库中的密码是否与新密码匹配,然后使用findOneAndUpdate它来更新密码是否符合您的条件。

另外,请允许我添加一个强制性提醒,永远不要将用户的密码明文存储在数据库中。您应该查找密码哈希最佳实践并实施这些实践,但这超出了此问题/答案的范围。


推荐阅读