您需要将查询useFindAndModify中的选项设置为false,如docs中所述。
(搜索关键字目前支持的选项有)
'useFindAndModify':默认为真。设置为 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 文档 (Click here) 中针对提到的这些弃用进行了更新:
Mongoose 的 findOneAndUpdate() 早于 MongoDB 驱动程序的
findOneAndUpdate() 函数,所以它使用 MongoDB 驱动程序的
findAndModify() 函数。
您可以通过三种或更多方式避免使用FindAndModify:
- 在全局级别:将选项设置为 false。
// Make Mongoose use `findOneAndUpdate()`. Note that this option is `true`
// by default, you need to set it to false.
mongoose.set('useFindAndModify', false);
- 在连接级别:我们可以使用连接选项进行配置:
mongoose.connect(uri, { useFindAndModify: false });
- 在查询级别:
await ModelName.findOneAndUpdate({matchQuery},
{$set: updateData}, {useFindAndModify: false});