英文:
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
istrue
, or sends anupdateOne
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论