且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

猫鼬:findOneAndUpdate不返回更新的文档

更新时间:2023-11-09 20:44:40

为什么会这样?

默认是返回未更改的原始文档.如果要返回更新后的新文档,则必须传递一个附加参数:new属性设置为true的对象.

Why this happens?

The default is to return the original, unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: an object with the new property set to true.

猫鼬文档:

Query#findOneAndUpdate

Model.findOneAndUpdate(conditions, update, options, (error, doc) => {
  // error: any errors that occurred
  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
});

可用选项

  • new:bool-如果为 true ,则返回经过修改的文档,而不是原始文档. 默认为假(已在4.0中更改)
  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

解决方案

如果要在doc变量中更新结果,请通过{new: true}:

Solution

Pass {new: true} if you want the updated result in the doc variable:

//                                                         V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});