MongoDB mongoose collection.find选项弃用警告

Mon*_*ffy 28 javascript mongoose mongodb nosql node.js

在使用collection.find我查询文档时,我开始在控制台中收到以下警告

DeprecationWarning:不推荐使用collection.find选项[fields],将在以后的版本中删除

我为什么看到这个,我该如何解决这个问题?(可能的选择)

编辑:查询已添加

Session
        .find({ sessionCode: '18JANMON', completed: false })
        .limit(10)
        .sort({time: 1})
        .select({time: 1, sessionCode: 1});
Run Code Online (Sandbox Code Playgroud)

猫鼬版本5.2.9

use*_*814 53

更新:

5.2.10已发布,可从此处下载.

使用mongoose.set('useCreateIndex', true);mongooose createIndex在mongodb本机驱动程序上调用该方法.

有关文档的更多信息,请查看页面 https://mongoosejs.com/docs/deprecations

有关该问题及其修复的更多信息, 请访问https://github.com/Automattic/mongoose/issues/6880

原答案:

Mongoose 5.2.9版本将本机mongodb驱动程序升级到3.1.3,其中添加了更改以在调用不推荐使用的本机驱动程序方法时抛出警告消息.

fields选项已弃用,并替换为projection选项.

您将不得不等待mongoose在其末尾进行更改以使用投影替换fields选项.该修复程序计划在5.2.10发布.

暂时你可以回到5.2.8,这将取消所有弃用警告.

npm install mongoose@5.2.8
Run Code Online (Sandbox Code Playgroud)

对于所有其他已弃用的警告,您必须逐个处理它们.

使用其他收集方法时,您将看到其他弃用警告.

DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
DeprecationWarning: collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.
DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Run Code Online (Sandbox Code Playgroud)

findOne*默认情况下,所有mongoose write方法findAndModify都使用mongodb本机驱动程序中不推荐使用的方法.

使用mongoose.set('useFindAndModify', false);mongooose findOne*在mongodb本机驱动程序上调用适当的方法.

对于removeupdate更换这些电话delete*update*分别的方法.

用于分别saveinsert*/ update*方法替换这些调用.


小智 7

mongoose.connect('your db url', {
  useCreateIndex: true,
  useNewUrlParser: true
})
Run Code Online (Sandbox Code Playgroud)

要么

mongoose.set('useCreateIndex', true)
mongoose.connect('your db url', { useNewUrlParser: true })
Run Code Online (Sandbox Code Playgroud)

  • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和/或文档链接.如果没有一些短语,原始代码片段就不是很有用.你也可以找到[如何写出一个好的答案](https://stackoverflow.com/help/how-to-answer)非常有帮助.请编辑你的答案. (2认同)

Ish*_*dra 5

升级到 5.2.10 版本后。可以使用以下任何选项

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', {

  useCreateIndex: true,
  useNewUrlParser: true

})
.then(() => console.log('connecting to database successful'))
.catch(err => console.error('could not connect to mongo DB', err));
Run Code Online (Sandbox Code Playgroud)


或者

const mongoose = require('mongoose');

mongoose.set('useCreateIndex', true);

mongoose.connect('mongodb://localhost/test',{

    useNewUrlParser: true

})
.then(() =>  console.log('connecting to database successful') )
.catch(err =>  console.error('could not connect to mongo DB', err) );
Run Code Online (Sandbox Code Playgroud)