【问题标题】:error when updating user password with bcrypt in mongodb在 mongodb 中使用 bcrypt 更新用户密码时出错
【发布时间】:2021-05-04 06:14:23
【问题描述】:
const {password, value} = body.password;

// compares the old and new password

const passwordMatch = await bcrypt.compare(password, student.password);
if(!passwordMatch) return res.status(400).json({message:"passwords do not match"})
                        
//hashes the password

const salt = await bcrypt.genSalt();
const hashedPassword = await bcrypt.hash(value, salt);
student.password = hashedPassword;

我正在使用“save()”来保存文档

下面是我遇到的错误

"error": {
        "errors": {
            "password": {
                "stringValue": "\"{ password: 'abcde', value: '123456' }\"",
                "kind": "string",
                "value": {
                    "password": "abcde",
                    "value": "123456"
                },
                "path": "password",
                "reason": null
            }
        },
        "_message": "Secondary validation failed",
        "message": "Secondary validation failed: password: Cast to string failed for value \"{ password: 'abcde', value: '123456' }\" at path \"password\""
    }

有什么帮助吗?我正在使用节点、快递和 mongodb。我也在使用邮递员进行测试。我无法弄清楚可能导致此问题的原因。

下面是输入的结构(即req.body)

{
    "password": {
        "password": "abcde",
        "value": "123456"
    }
}

在哪里

  • password = 旧密码(即数据库中存在的密码)
  • value = 要更改的新密码

【问题讨论】:

  • 完全添加您的路线和架构,

标签: database mongodb express authentication passwords


【解决方案1】:

假设您从某个地方获取了 students._id

router.patch("/", async (req, res) => {
  try {
    const { password, newPassword } = req.body;
    const validPass = await bcrypt.compare(password, student.password);
    if (!validPass) return res.status(400).json("Invalid Password");

    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);
    await Student.findOneAndUpdate(
      { _id: student._id },
      { $set: { password: hashedPassword } },{ useFindAndModify: false }
    );
    res.status(200).send("Password Updated");
  } catch (err) {
    res.status(400).send({ message: err });
  }
});

你会看到这样的东西,如果这有帮助,请告诉我

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多