node.js - DeprecationWarning : collection. findAndModify 已弃用。改用 findOneAndUpdate、findOneAndReplace 或 findOneAndDelete?

标签 node.js mongodb mongoose deprecated

我正在使用 Mongoose findOneAndUpdate 但仍然收到错误,

DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.

但我什至没有使用 findAndModify,为什么它会将我的查询转换为 findAndModify

最佳答案

您需要将查询useFindAndModify 中的选项设置为false,如docs 中所述.

(搜索关键字目前支持的选项有)

'useFindAndModify': true by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().

如果你看到mongoose的定义文件,其中提到它调用findAndModify更新命令。

 /**
  * Issues a mongodb findAndModify update command.
  * Finds a matching document, updates it according to the update arg, 
    passing any options,
  * and returns the found document (if any) to the callback. The query 
    executes immediately
  * if callback is passed else a Query object is returned.
  */
 findOneAndUpdate(): DocumentQuery<T | null, T>;

最近在 mongoose 文档 (Click here) 中更新了这些弃用的地方:

Mongoose's findOneAndUpdate() long pre-dates the MongoDB driver's findOneAndUpdate() function, so it uses the MongoDB driver's findAndModify() function instead.

您可以通过三种或更多方式避免使用FindAndModify:

  1. 在全局级别:将选项设置为 false。
// Make Mongoose use `findOneAndUpdate()`. Note that this option is `true`
// by default, you need to set it to false.
mongoose.set('useFindAndModify', false);
  1. 在连接级别:我们可以使用连接选项进行配置:
    mongoose.connect(uri, { useFindAndModify: false });
  1. 在查询级别:
   await ModelName.findOneAndUpdate({matchQuery},
   {$set: updateData}, {useFindAndModify: false});

关于node.js - DeprecationWarning : collection. findAndModify 已弃用。改用 findOneAndUpdate、findOneAndReplace 或 findOneAndDelete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572852/

相关文章:

javascript - 如何编写以 if 条件作为第一个语句的 Promise 链?

javascript - Ajax GET : multiple data-specific calls, 或更少的特定调用?

node.js - Loopback JS模型与MongoDB的连接

node.js - Mongoose 架构类型字符串不起作用

javascript - 从 mongoose.find() 创建对象集

node.js - KeystoneJS 自定义内容类型

javascript - 如何将 Node 模块的 require 转换为 es6 import/export

c++ - 我可以(应该)将我的 DBClientConnection 用作全局变量吗?

php - 我需要介绍 MongoDB/NoSQL 数据库

javascript - 按已过滤子文档数组元素的计数排序