Mongoose解决MongoDB弃用警告

MongoDB弃用警告

原文链接:https://mongoosejs.com/docs/deprecations.html#-findandmodify-

MongoDB Node.js驱动程序中有几个弃用,Mongoose提供了解决这些弃用警告的选项

摘要

要修复所有弃用警告,请按照以下步骤操作:

  • mongoose.set('useNewUrlParser', true)
  • mongoose.set('useFindAndModify', false)
  • mongoose.set('useCreateIndex', true)
  • update()替换为updateOne(),updateMany(),replaceOne()
  • remove()替换为deleteOne()deleteMany()
  • count()替换为countDocuments(), 除非您想要计算整个集合中有多少文档(没有过滤器)。在后一种情况下,使用estimatedDocumentCount()

useNewUrlParser选项

默认情况下,mongoose.connect()会打印出以下警告:

DeprecationWarning: current URL string parser is deprecated, and will be
removed in a future version. To use the new parser, pass option
{ useNewUrlParser: true } to MongoClient.connect.

  
  

    MongoDB Node.js驱动程序重写了用于解析MongoDB连接字符串的工具。因为这是一个很大的变化,所以他们将新的连接字符串解析器放在一个标志后面。要打开此选项,请将useNewUrlParser选项传递给 mongoose.connect()mongoose.createConnection()

    mongoose.connect(uri, { useNewUrlParser: true })
    mongoose.createConnection(uri, { useNewUrlParser: true })
    
      
      

      您还可以将全局选项设置useNewUrlParser为默认情况下为每个连接打开。

      mongoose.set('useNewUrlParser', true)
      
        
        

        要测试您的应用{ useNewUrlParser: true },您只需要检查您的应用是否成功连接。一旦Mongoose成功连接,URL解析器就不再重要了。

        usefindAndModify选项

        如果使用Model.findOneAndUpdate(),默认情况下会看到以下弃用警告之一。

        DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-
        DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
        
          
          

          Mongoose很findOneAndUpdate()早就预定了MongoDB驱动程序的findOneAndUpdate() 功能,所以它使用了MongoDB驱动程序的findAndModify()功能。您可以使用useFindAndModify全局选项选择使用MongoDB驱动程序的功能。

          // 要让 mongoose 使用 `findOneAndUpdate()`.注意选项设置为`true`
          // 默认选项为 false.
          mongoose.set('useFindAndModify', false);
          
            
            

            您还可以通过连接选项进行配置useFindAndModify

            mongoose.connect(uri, { useFindAndModify: false });
            
              
              

              此选项会影响以下模型和查询功能。没有任何故意向后突破的更改,因此您应该能够在不更改任何代码的情况下启用此选项。

              useCreateIndex选项

              如果在Mongoose模式中定义索引,则会看到以下弃用警告。

              DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes
              instead.
              
                
                
              • 1
              • 2

              默认情况下,Mongoose 5.x调用MongoDB驱动程序的ensureIndex()函数。MongoDB驱动程序不赞成使用此函数createIndex()。设置useCreateIndex全局选项以选择使用Mongoose createIndex()

              mongoose.set('useCreateIndex', true);
              
                
                
              • 1

              您还可以通过连接选项进行配置。

              mongoose.connect(uri, { useCreateIndex: true });
              
                
                
              • 1

              使用该useCreateIndex 选项不会有意向后更改,因此您应该能够在不更改任何代码的情况下启用此选项。

              remove()

              不推荐使用MongoDB驱动程序的remove()函数,推荐使用deleteOne()deleteMany()。这符合MongoDB CRUD规范,该规范旨在为所有MongoDB驱动程序的CRUD操作提供一致的API。

              DeprecationWarning: collection.remove is deprecated. Use deleteOne,
              deleteMany, or bulkWrite instead.
              
                
                
              • 1
              • 2

              要删除此弃用警告,请替换remove()with的 任何用法deleteMany()除非您指定single选项remove()。该single 选项仅限remove()于删除最多一个文档,因此您应该替换remove(filter, { single: true })deleteOne(filter)

              // Replace this:
              MyModel.remove({ foo: 'bar' });
              // With this:
              MyModel.deleteMany({ foo: 'bar' });
              // Replace this:
              MyModel.remove({ answer: 42 }, { single: true });
              // With this:
              MyModel.deleteOne({ answer: 42 });
              
                
                

                update()

                remove(),该update()功能是明确弃用,更赞成使用updateOne()updateMany()replaceOne()功能。除非使用选项,否则应替换 update()updateOne()multi``overwrite

                //Replace this:
                MyModel.update({ foo: 'bar' }, { answer: 42 });
                // with this:
                MyModel.updateOne({ foo: 'bar' }, { answer: 42 });
                // If you use `overwrite: true`, you should use `replaceOne()` instead:
                MyModel.update(filter, update, { overwrite: true });
                // Replace with this:
                MyModel.replaceOne(filter, update);
                // If you use `multi: true`, you should use `updateMany()` instead:
                MyModel.update(filter, update, { multi: true });
                // Replace with this:
                MyModel.updateMany(filter, update);
                
                  
                  

                  count()

                  MongoDB服务器已弃用该count()函数,而支持两个独立的函数,countDocuments()estimatedDocumentCount()

                  DeprecationWarning: collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead
                  
                    
                    

                    两者之间的区别是countDocuments()可以接受像这样的过滤参数find()。该estimatedDocumentCount() 功能更快,但只能告诉您集合中的文档总数。你不能传递filterestimatedDocumentCount()

                    要进行迁移,请替换count()countDocuments() 除非您未传递任何参数count()。如果您使用count()计算集合中的所有文档而不是计算与查询匹配的文档,请使用 estimatedDocumentCount()而不是countDocuments()

                    // Replace this:
                    MyModel.count({ answer: 42 });
                    // With this:
                    MyModel.countDocuments({ answer: 42 });
                    // If you're counting all documents in the collection, use
                    // `estimatedDocumentCount()` instead.
                    MyModel.count();
                    // Replace with:
                    MyModel.estimatedDocumentCount();
                    // Replace this:
                    MyModel.find({ answer: 42 }).count().exec();
                    // With this:
                    MyModel.find({ answer: 42 }).countDocuments().exec();
                    // Replace this:
                    MyModel.find().count().exec();
                    // With this, since there's no filter
                    MyModel.find().estimatedDocumentCount().exec();
                    
                      
                      

                      GridStore

                      如果您正在使用gridfs-stream,您将看到以下弃用警告:

                      DeprecationWarning: GridStore is deprecated, and will be removed in a
                      future version. Please use GridFSBucket instead.
                      
                        
                        

                        这是因为gridfs-stream依赖于已弃用的MongoDB驱动程序类。您应该使用MongoDB驱动程序自己的 streaming API

                        // Replace this:
                        const conn = mongoose.createConnection('mongodb://localhost:27017/gfstest');
                        const gfs = require('gridfs-store')(conn.db);
                        const writeStream = gfs.createWriteStream({ filename: 'test.dat' });
                        // With this:
                        const conn = mongoose.createConnection('mongodb://localhost:27017/gfstest');
                        const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db);
                        const writeStream = gridFSBucket.openUploadStream('test.dat');
                        
                        • 3
                          点赞
                        • 10
                          收藏
                          觉得还不错? 一键收藏
                        • 0
                          评论

                        “相关推荐”对你有帮助么?

                        • 非常没帮助
                        • 没帮助
                        • 一般
                        • 有帮助
                        • 非常有帮助
                        提交
                        评论
                        添加红包

                        请填写红包祝福语或标题

                        红包个数最小为10个

                        红包金额最低5元

                        当前余额3.43前往充值 >
                        需支付:10.00
                        成就一亿技术人!
                        领取后你会自动成为博主和红包主的粉丝 规则
                        hope_wisdom
                        发出的红包
                        实付
                        使用余额支付
                        点击重新获取
                        扫码支付
                        钱包余额 0

                        抵扣说明:

                        1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
                        2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

                        余额充值