findOneAndUpdate 和 update 的 mongoose 区别

mongoose difference of findOneAndUpdate and update

findOneAndUpdate 和 update 有什么区别?

两者都接受查询条件和更新文档。

.findOneAndUpdate method issues a mongodb .findAndModify update command and returns the found document (if any) to the callback or return the modified document rather than the original if the new option is true and the .update execute the query as an update()操作。

好吧,这里有 .update() and .findAndModify() 的相应文档,这是 .findOneAndUpdate() 的根方法。

但主要区别有:

  • update():旨在对集合中与其查询条件匹配的 "one or more" 文档执行原子更新操作。它 return 是其响应中修改文档的数量。

  • findOneAndUpdate():目的是处理 "singular" 文档的更新语句,以及检索该文档的内容"singular" 文档。状态 returned 取决于传递给操作的 "new" 选项的值。其中 true "modified" 文档是 returned。其中 false "original" 文档在任何修改之前 returned。后一种形式是默认选项。

简而言之。一个是在 "bulk" 中修改,而不用担心结果中的文档内容。另一个是修改单个文档和return结果中的文档内容。

这就是区别。

请注意,在 findOneAndXXX 方法中有一个选项 returnNewDocument,它的默认值为 true。如果您使用的是 node.js 驱动程序,则选项称为 returnOriginal