当模式名称为User时,解释一下await user.save()的工作原理。

huangapple go评论65阅读模式
英文:

Explain to me how await user.save() works when schema name is User

问题

module.exports.updatePassword = async (req, res) => {
  const { userId } = req.params;
  const { oldPassword, newPassword } = req.body;

  try {
    const user = await User.findById(userId);

    const isPasswordValid = await user.isValidPassword(oldPassword);

    if (!isPasswordValid) {
      return res.status(401).json({ message: "旧密码不正确" });
    }

    const salt = await bcrypt.genSalt(10);
    const newHashedPassword = await bcrypt.hash(newPassword, salt);
    const oldHashedPassword = user.password;

    if (oldHashedPassword === newHashedPassword) {
      return res
        .status(400)
        .json({
          message: "新密码不能与旧密码相同",
        });
    }

    user.password = newHashedPassword;
    await user.save();

    return res.json({ message: "密码更新成功" });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: "服务器错误" });
  }
};
英文:
module.exports.updatePassword = async (req, res) => {
  const { userId } = req.params;
  const { oldPassword, newPassword } = req.body;

  try {
    const user = await User.findById(userId);

    const isPasswordValid = await user.isValidPassword(oldPassword);

    if (!isPasswordValid) {
      return res.status(401).json({ message: "Incorrect old password" });
    }

    const salt = await bcrypt.genSalt(10);
    const newHashedPassword = await bcrypt.hash(newPassword, salt);
    const oldHashedPassword = user.password;

    if (oldHashedPassword === newHashedPassword) {
      return res
        .status(400)
        .json({
          message: "New password should not be the same as old password",
        });
    }

    user.password = newHashedPassword;
    await user.save();

    return res.json({ message: "Password updated successfully" });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: "Server error" });
  }
};

This is the userSchema with name User but in above code user.save() is used to update data - can anyone explain this?

exprots Users = mongoose.model('users', userSchem)

答案1

得分: 0

User.findOne的调用会返回一个Document,它被存储在变量user中。

作为一个Document实例,该对象将具有在原型上定义的所有方法:https://mongoosejs.com/docs/api/document.html

save 是其中之一,你可以使用user.save()来调用它。

根据文档,save 方法

Saves this document by inserting a new document into the database if document.isNew is true, or sends an updateOne operation only with the modifications to the database; it does not replace the whole document in the latter case.

英文:

The call to User.findOne returns a Document, which is stored in the variable user.

As an instance of a Document, that object will possess all of the methods defined on the prototype: https://mongoosejs.com/docs/api/document.html

save is one such method, which you called with user.save()

From the documentation, the save method

>Saves this document by inserting a new document into the database if document.isNew is true, or sends an updateOne operation only with the modifications to the database, it does not replace the whole document in the latter case.

huangapple
  • 本文由 发表于 2023年3月7日 03:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定