DeprecationWarning:不推荐使用collection.findAndModify。请改用findOneAndUpdate,findOneAndReplace或findOneAndDelete?

问题描述 投票:19回答:4

我正在使用mongoose findOneAndUpdate但仍然得到错误,

DeprecationWarning:不推荐使用collection.findAndModify。请改用findOneAndUpdate,findOneAndReplace或findOneAndDelete。

但我甚至不使用findAndModify,为什么它将我的查询转换为findAndModify

node.js mongodb mongoose deprecated
4个回答
35
投票

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

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

'useFindAndModify':默认为true。设置为false以使findOneAndUpdate()和findOneAndRemove()使用本机findOneAndUpdate()而不是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 docs(Click here)中对这些弃用进行了更新,如下所述:

Mongoose的findOneAndUpdate()很早就预定了MongoDB驱动程序的findOneAndUpdate()函数,因此它使用了MongoDB驱动程序的findAndModify()函数。

有三种方法可以避免使用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});


12
投票

像这样全局更改mongoose配置:

mongoose.set('useFindAndModify', false);

或者传递查询字符串中的选项,如下所示:

Person.findOneAndUpdate({_id: id}, {$set: body}, {new: true, useFindAndModify: false}).then(..

您还可以管理其他猫鼬弃用警告,如docs所述

mongoose.set('useNewUrlParser', true);
mongoose.set('useCreateIndex', true);

而已。


5
投票

您还可以通过需求选项useNewUrlParser传递连接处的选项。看看以下 - > https://mongoosejs.com/docs/deprecations.html

mongoose.connect(config.MONGODB_URI, { useNewUrlParser: true, useFindAndModify: false}); 

0
投票

您必须更改您的连接方法选项以摆脱它:

mongoose.connect("mongodb://localhost/DB_Name", {
  keepAlive: true,
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false
});

你可以这样使用。

© www.soinside.com 2019 - 2024. All rights reserved.