首页 文章

MongoDB mongoose collection.find选项弃用警告

提问于
浏览
25

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

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

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

EDIT: Query Added

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

Mongoose version 5.2.9

4 回答

  • 2

    Update:

    5.2.10已发布并可供下载here .

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

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

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

    Original Answer:

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

    不推荐使用fields选项,并将其替换为 projection 选项 .

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

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

    npm install mongoose@5.2.8
    

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

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

    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.
    

    默认情况下,所有 findOne* mongoose写入方法都使用findAndModify方法,该方法在mongodb本机驱动程序中已弃用 .

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

    对于 removeupdate 分别用 delete*update* 方法替换这些调用 .

    对于 save ,分别用 insert* / update* 方法替换这些调用 .

  • 47
    mongoose.connect('your db url', {
      useCreateIndex: true,
      useNewUrlParser: true
    })
    

    要么

    mongoose.set('useCreateIndex', true)
    mongoose.connect('your db url', { useNewUrlParser: true })
    
  • 6

    升级到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));
    

    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) );
    
  • 3

    您可以执行 npm install mongoose@5.2.8 ,这将帮助您返回到不会显示任何弃用警告的早期版本

相关问题