node.js - 更新 findOne()/find()/findById() 返回的文档 - mongoose
问题描述
我想知道是否有任何方法可用于更改 mongoose 返回的文档对象的可用字段的值find()
,findOne()
以及findById()
方法并使用应用于数据库的更改来更新它们。下面的代码片段是我期望完成我想要的工作:
User.findOne({ email: email })
.then(user => {
if (user) {
user.fieldToUpdate = "Updated value"; // Here I'm getting the field and updating it with the new value;
user.save().then().catch(); // Here I'm updating the document to the database, expecting for a promise object
} else {
const error = new Error("No such user in the database.");
error.httpStatusCode = 422;
next(error);
}
})
.catch(error => {
next(error);
});
解决方案
您编写的代码片段可以正常工作,但如果您只需要更新找到的文档:
User.findOneAndUpdate({ email }, { email: 'sample@test.com' })
.then((err, user) => {
//
}
推荐阅读
- c# - 反序列化时如何在.net核心API FromBody参数中自动将数字转换为字符串?
- javascript - javascript中嵌套数组的最佳实践
- python - 这些 `.` 属性绑定在 `functools.partial` 的实现中是必需的吗?
- ruby - 如何编写具有多种可能结果的场景
- azure - Azure Function 无法加载 ApplicationInsights 程序集
- asp.net - 将旧的 ASP url 重定向到新的 Wordpress 页面
- python - 无法使用 XPath 从网页获取价格
- python - 为什么调整模态 Qt 对话框的大小使其不再停留在 ctwm 窗口管理器中其父级的顶部?
- python - 使用 lambda 调用带有参数但传递索引而不是项的函数
- google-apps-script - 如何将 drive.file 范围用于独立的谷歌应用程序脚本