更新文档并返回更新的文档

时间:2020-03-12 18:25:55

标签: node.js mongodb express mongoose

const _id = req.params.id;
let tire = await TireModel.findOne({ _id });
tire = await tire.update({description : "new description"});
console.log(tire);

当我运行这段代码时,我希望轮胎是更新的代码,但它会在数据库中返回操作的结果。我已经尝试过{new:true}选项。

2 个答案:

答案 0 :(得分:1)

您可以使用findOneAndUpdate()功能。

const filter = { name: 'Jean-Luc Picard' };
const update = { age: 59 };

// `doc` is the document _after_ `update` was applied because of
// `new: true`
let doc = await Character.findOneAndUpdate(filter, update, {
  new: true
});
doc.name; // 'Jean-Luc Picard'
doc.age; // 59

更多信息https://mongoosejs.com/docs/tutorials/findoneandupdate.html

答案 1 :(得分:1)

使用findOne查找文档后,可以更新其字段,然后使用save()方法:

const _id = req.params.id;
let tire = await TireModel.findOne({ _id });

if (tire) {
  tire.description = "new description";
  tire = await tire.save();
  console.log(tire);
} else {
  //todo
}
相关问题