mongodb - findByIdAndUpdate 不更新文档
问题描述
我正在尝试使用 findByIdAndUpdate 将字段更新到文档中。我尝试更新的字段在条形模型中定义。而且我还可以保证req.body.bookId
有一个有效的身份证。
这是我的请求的样子,
app.patch("/foo", async (req, res) => {
try {
await validateId(req.body.bookId);
let doc = await Bar.findByIdAndUpdate(
req.body.bookId,
{ DateT: Date.now() },
{ new: true }
);
res.send(doc);
} catch (err) {
console.log(err);
}
});
条形图,
const mongoose = require("mongoose");
const barSchema = mongoose.Schema({
bookId: {
type: String,
unique: true,
},
DateT: {
type: Date,
default: null,
},
});
module.exports = mongoose.model("Bar", barSchema);
解决方案
使用updateOne
,当你使用时async
不要.then()
使用try/catch
测试它:
app.patch("/foo", async (req, res) => {
try {
let doc = await Bar.updateOne(
{ bookId : req.body.bookId },
{ DateT: Date.now() },
{ new: true }
);
res.send(doc);
} catch (error) {
console.log(error);
}
});
推荐阅读
- camunda - 历史外部任务日志
- reactjs - ReactJS - 使用 React Hooks 去抖动 - 引发我无法解决的错误。解析错误
- javascript - 如何在html中禁用基于“id”或“class”的选择下拉菜单
- c# - Zkteco 如何按日志周期读取出勤率?
- mysql - 一张表的许多外键
- angular - 令牌拦截器在 Angular 8 中不起作用
- google-apps-script - 将文本字符串添加到新列 (A) 并重复每一行,直到到达在原始列 (B) 中具有预先存在值的某一行
- c - c中的快速排序文件处理
- javascript - 如何编写javascript函数来克隆表中的行?
- javascript - 如何根据Javascript中的多个数组属性取消组合对象数组