我正在使用 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
:
- 在全局级别:将选项设置为 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});
关于node.js - DeprecationWarning : collection. findAndModify 已弃用。改用 findOneAndUpdate、findOneAndReplace 或 findOneAndDelete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572852/