【问题标题】:通过将 useNewUrlParser 设置为 true 来避免“不推荐使用当前 URL 字符串解析器”警告
【发布时间】:2018-10-31 01:49:55
【问题描述】:

我有一个数据库包装类,它与某个 MongoDB 实例建立连接:

async connect(connectionString: string): Promise<void> {
        this.client = await MongoClient.connect(connectionString)
        this.db = this.client.db()
}

这给了我一个警告:

(node:4833) DeprecationWarning:当前 URL 字符串解析器已被弃用,并将在未来版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。

connect() 方法接受 MongoClientOptions 实例作为第二个参数。但它没有名为useNewUrlParser 的属性。我还尝试在连接字符串中设置这些属性,如下所示:mongodb://127.0.0.1/my-db?useNewUrlParser=true 但它对这些警告没有影响。

那么我该如何设置useNewUrlParser 来消除这些警告呢?这对我很重要,因为脚本应该作为 cron 运行,并且这些警告会导致垃圾邮件垃圾邮件。

我在3.1.0-beta4 版本中使用mongodb 驱动程序,并在3.0.18 中使用相应的@types/mongodb 包。它们都是使用npm install 的最新版本。

解决方法

使用旧版本的 mongodb 驱动:

"mongodb": "~3.0.8",
"@types/mongodb": "~3.0.18"

【问题讨论】:

  • 这来自beta 版本,它在周末以某种方式在 npm 上发布。在 API 真正完成之前不要担心。安装稳定版本是正确的做法。
  • mongodb 3.0.0 以上简单添加 mongoose.connect("mongodb://localhost:portnumber/YourDB", { useNewUrlParser: true })

标签: node.js mongodb typescript express mongoose


【解决方案1】:

(node:16596) DeprecationWarning: 当前 URL 字符串解析器是 已弃用,并将在未来的版本中删除。要使用新 解析器,将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。 (使用node --trace-deprecation ... 显示警告的位置 已创建)(节点:16596)[MONGODB 驱动程序] 警告:当前服务器 发现和监控引擎已弃用,并将在 未来的版本。使用新的服务器发现和监控 引擎,将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。

用法:

async connect(connectionString: string): Promise<void> {
        this.client = await MongoClient.connect(connectionString, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  })
        this.db = this.client.db()
}

【讨论】:

    【解决方案2】:

    我使用 mlab.com 作为 MongoDB 数据库。我将连接字符串分隔到另一个名为 config 的文件夹中,并在文件 keys.js 中保留了连接字符串:

    module.exports = {
      mongoURI: "mongodb://username:password@ds147267.mlab.com:47267/projectname"
    };

    而服务器代码是

    const express = require("express");
    const mongoose = require("mongoose");
    const app = express();
    
    // Database configuration
    const db = require("./config/keys").mongoURI;
    
    // Connect to MongoDB
    
    mongoose
      .connect(
        db,
        { useNewUrlParser: true } // Need this for API support
      )
      .then(() => console.log("MongoDB connected"))
      .catch(err => console.log(err));
    
    app.get("/", (req, res) => res.send("hello!!"));
    
    const port = process.env.PORT || 5000;
    
    app.listen(port, () => console.log(`Server running on port ${port}`)); // Tilde, not inverted comma

    你需要像我上面那样在连接字符串后面写{ useNewUrlParser: true }

    简单地说,你需要做的:

    mongoose.connect(connectionString,{ useNewUrlParser: true } 
    // Or
    MongoClient.connect(connectionString,{ useNewUrlParser: true } 
        

    【讨论】:

      【解决方案3】:

      您需要在mongoose.connect() 方法中添加{ useNewUrlParser: true }

      mongoose.connect('mongodb://localhost:27017/Notification',{ useNewUrlParser: true });
      

      【讨论】:

      • 这个答案与几个月前发布的其他答案相同
      • 这与之前的答案有何不同?
      • @PeterMortensen 请检查最先发布答案的日期
      【解决方案4】:
      const mongoose = require('mongoose');
      
      mongoose
        .connect(connection_string, {
          useNewUrlParser: true,
          useUnifiedTopology: true,
          useCreateIndex: true,
          useFindAndModify: false,
        })
        .then((con) => {
          console.log("connected to db");
        });
      

      尝试使用这个

      【讨论】:

        【解决方案5】:

        没有什么可以改变的。只传入连接函数{useNewUrlParser: true }

        这将起作用:

            MongoClient.connect(url, {useNewUrlParser:true,useUnifiedTopology: true }, function(err, db) {
                if(err) {
                    console.log(err);
                }
                else {
                    console.log('connected to ' + url);
                    db.close();
                }
            })
        

        【讨论】:

        • 正是我需要的,但警告信息仍然存在:-S
        • 为我工作,不再有警告。
        【解决方案6】:

        这很适合我:

        mongoose.set("useNewUrlParser", true);
        mongoose.set("useUnifiedTopology", true);
        mongoose
          .connect(db) //Connection string defined in another file
          .then(() => console.log("Mongo Connected..."))
          .catch(() => console.log(err));
        

        【讨论】:

          【解决方案7】:

          以下为我工作 对于mongoose 版本5.9.16

          const mongoose = require('mongoose');
          
          mongoose.set('useNewUrlParser', true);
          mongoose.set('useFindAndModify', false);
          mongoose.set('useCreateIndex', true);
          mongoose.set('useUnifiedTopology', true);
          
          mongoose.connect('mongodb://localhost:27017/dbName')
              .then(() => console.log('Connect to MongoDB..'))
              .catch(err => console.error('Could not connect to MongoDB..', err))
          

          【讨论】:

            【解决方案8】:

            以下对我有用

            const mongoose = require('mongoose');
            
            mongoose.connect("mongodb://localhost/playground", { useNewUrlParser: true,useUnifiedTopology: true })
            .then(res => console.log('Connected to db'));
            

            mongoose 版本是5.8.10

            【讨论】:

            • 这个也对我有用。我正在使用--body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.9.14"
            【解决方案9】:

            你只需要在连接数据库之前进行如下设置:

            const mongoose = require('mongoose');
            
            mongoose.set('useNewUrlParser', true);
            mongoose.set('useFindAndModify', false);
            mongoose.set('useCreateIndex', true);
            mongoose.set('useUnifiedTopology', true);
            
            mongoose.connect('mongodb://localhost/testaroo');
            

            还有,

            Replace update() with updateOne(), updateMany(), or replaceOne()
            Replace remove() with deleteOne() or deleteMany().
            Replace count() with countDocuments(), unless you want to count how many documents are in the whole collection (no filter).
            In the latter case, use estimatedDocumentCount().
            

            【讨论】:

            • 应该是最佳答案。对我来说,所有其他答案都失败了。
            • 如果对您有用,请将答案标记为correct。它也对我有用!
            【解决方案10】:

            我正在为我的项目使用猫鼬版本 5.x。在需要 mongoose 包后,全局设置值如下。

            const mongoose = require('mongoose');
            
            // Set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
            mongoose.set('useNewUrlParser', true);
            

            【讨论】:

              【解决方案11】:

              Express.js、API调用案例和发送JSON内容的完整示例如下:

              ...
              app.get('/api/myApi', (req, res) => {
                MongoClient.connect('mongodb://user:password@domain.com:port/dbname',
                  { useNewUrlParser: true }, (err, db) => {
              
                    if (err) throw err
                    const dbo = db.db('dbname')
                    dbo.collection('myCollection')
                      .find({}, { _id: 0 })
                      .sort({ _id: -1 })
                      .toArray(
                        (errFind, result) => {
                          if (errFind) throw errFind
                          const resultJson = JSON.stringify(result)
                          console.log('find:', resultJson)
                          res.send(resultJson)
                          db.close()
                        },
                      )
                  })
              }
              

              【讨论】:

                【解决方案12】:

                ECMAScript 8/await 更新

                不正确的ECMAScript 8 demo code MongoDB inc provides 也会产生此警告。

                MongoDB提供以下建议,不正确

                要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。

                这样做会导致以下错误:

                TypeError:executeOperation 的最后一个参数必须是回调

                必须将选项提供给new MongoClient

                请看下面的代码:

                const DATABASE_NAME = 'mydatabase',
                    URL = `mongodb://localhost:27017/${DATABASE_NAME}`
                
                module.exports = async function() {
                    const client = new MongoClient(URL, {useNewUrlParser: true})
                    var db = null
                    try {
                        // Note this breaks.
                        // await client.connect({useNewUrlParser: true})
                        await client.connect()
                        db = client.db(DATABASE_NAME)
                    } catch (err) {
                        console.log(err.stack)
                    }
                
                    return db
                }
                

                【讨论】:

                  【解决方案13】:

                  如果usernamepassword@ 字符,那么像这样使用它:

                  mongoose
                      .connect(
                          'DB_url',
                          { user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
                      )
                      .then(() => console.log('Connected to MongoDB'))
                      .catch(err => console.log('Could not connect to MongoDB', err));
                  

                  【讨论】:

                    【解决方案14】:

                    连接字符串格式必须是mongodb://user:password@host:port/db

                    例如:

                    MongoClient.connect('mongodb://user:password@127.0.0.1:27017/yourDB', { useNewUrlParser: true } )
                    

                    【讨论】:

                    • 没有。 MongoClient.connect('mongodb://127.0.0.1:27017/yourDB', { useNewUrlParser: true } ) 也可以。
                    • 这与之前的答案有何不同?
                    【解决方案15】:

                    我认为您不需要添加{ useNewUrlParser: true }

                    您是否想使用新的 URL 解析器由您决定。最终,当 MongoDB 切换到新的 URL 解析器时,警告会消失。

                    Connection String URI Format中指定,不需要设置端口号。

                    只需添加{ useNewUrlParser: true } 即可。

                    【讨论】:

                    • 我添加了端口号,但仍然收到错误消息。我发现错误消息非常令人困惑和误导:为什么我会收到一条消息告诉我使用新格式,而实际上我使用的是旧格式并且它工作得很好......!!??
                    • 好问题!请注意,这是一个警告。不是错误。只有添加useNewUrlParser: true,警告才会消失。但这有点愚蠢,因为一旦 mongo 切换到新的 url 解析器,这个额外的参数就会过时。
                    • 你怎么知道端口号是新的 url 解析器所期望的?我找不到任何实际描述新 url 解析器是什么的东西
                    • @Brad,确实如此。我假设您需要添加端口号,但 Mongo 规范仍然提到端口号是可选的。我相应地更新了我的答案。
                    【解决方案16】:

                    下面突出显示的 mongoose 连接代码解决了 mongoose 驱动程序的警告:

                    mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
                    

                    【讨论】:

                    • 不适合我。仍然得到:(节点:35556)DeprecationWarning:当前的 URL 字符串解析器已被弃用,并将在未来的版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。
                    • 如果仍然无法正常工作,您必须将 server.js 或 app.js 保存在您提供数据库路径的任何位置尝试通过在 package.json 文件为时输入 npm install 删除并重新安装 node_modules
                    【解决方案17】:

                    我们使用的是:

                    mongoose.connect("mongodb://localhost/mean-course").then(
                      (res) => {
                       console.log("Connected to Database Successfully.")
                      }
                    ).catch(() => {
                      console.log("Connection to database failed.");
                    });
                    

                    → 这会导致 URL 解析器错误

                    正确的语法是:

                    mongoose.connect("mongodb://localhost:27017/mean-course" , { useNewUrlParser: true }).then(
                      (res) => {
                       console.log("Connected to Database Successfully.")
                      }
                    ).catch(() => {
                      console.log("Connection to database failed.");
                    });
                    

                    【讨论】:

                    • 添加一些描述
                    【解决方案18】:

                    这个问题可以通过给出端口号并使用这个解析器来解决:{useNewUrlParser: true}

                    解决办法可以是:

                    mongoose.connect("mongodb://localhost:27017/cat_app", { useNewUrlParser: true });
                    

                    它解决了我的问题。

                    【讨论】:

                    • 控制台本身提供了在connect 中添加useNewUrlParser property 的解决方案,但您的解决方案有所帮助。如此赞成!
                    【解决方案19】:

                    这就是我拥有它的方式。在我几天前更新 npm 之前,提示没有显示在我的控制台上。

                    .connect 有 URI、options 和 err 三个参数。

                    mongoose.connect(
                        keys.getDbConnectionString(),
                        { useNewUrlParser: true },
                        err => {
                            if (err) 
                                throw err;
                            console.log(`Successfully connected to database.`);
                        }
                    );
                    

                    【讨论】:

                      【解决方案20】:

                      检查您的mongo 版本:

                      mongo --version
                      

                      如果您使用版本 >= 3.1.0,请将您的 mongo 连接文件更改为 ->

                      MongoClient.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
                      

                      或你的猫鼬连接文件 ->

                      mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true });
                      

                      理想情况下,它是第 4 版功能,但 v3.1.0 及更高版本也支持它。详情请查看MongoDB GitHub

                      【讨论】:

                      • @AbhishekSinha 为什么使用 mongo >= 4.0.0?我正在使用 3.6.5,烦人的消息也消失了。
                      • 是的,解决了这个问题。基本上,它是 v4 功能,但 v3.1.0 及更高版本也支持新功能。
                      • 这是最好的,只是想补充一下,如果你有回调,尤其是错误,只需使用这个:mongoose.connect(dbUrl, { useNewUrlParser: true }, function(err) { console .log("mongoDB 已连接", err); })
                      【解决方案21】:

                      这些行也解决了所有其他弃用警告:

                      const db = await mongoose.createConnection(url, { useNewUrlParser: true });
                      mongoose.set('useCreateIndex', true);
                      mongoose.set('useFindAndModify', false);
                      

                      【讨论】:

                        【解决方案22】:

                        正如所指出的,驱动程序的3.1.0-beta4 版本从外观上看有点早“被释放到野外”。该版本是正在进行的工作的一部分,以支持即将发布的 MongoDB 4.0 版本中的新功能并进行一些其他 API 更改。

                        其中一个触发当前警告的更改是useNewUrlParser 选项,这是由于有关传递连接 URI 的实际工作方式的一些更改。稍后会详细介绍。

                        在事情“安定下来”之前,至少对于 3.0.x 版本的次要版本来说,它可能是 advisable to "pin"

                          "dependencies": {
                            "mongodb": "~3.0.8"
                          }
                        

                        这应该会阻止 3.1.x 分支安装在节点模块的“新”安装上。如果您已经安装了“最新”版本,即“beta”版本,那么您应该清理您的软件包(和 package-lock.json)并确保将其升级为 3.0.x 系列版本。

                        至于实际使用“新”连接 URI 选项,主要限制是在连接字符串中实际包含 port

                        const { MongoClient } = require("mongodb");
                        const uri = 'mongodb://localhost:27017';  // mongodb://localhost - will fail
                        
                        (async function() {
                          try {
                        
                            const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
                            // ... anything
                        
                            client.close();
                          } catch(e) {
                            console.error(e)
                          }
                        
                        })()
                        

                        这是新代码中更“严格”的规则。要点是当前代码本质上是“node-native-driver”(npm mongodb)存储库代码的一部分,而“新代码”实际上是从 mongodb-core 库导入的,该库“支持”“公共” " 节点驱动程序。

                        添加“选项”的目的是通过将选项添加到新代码来“缓解”转换,以便在代码中使用更新的解析器(实际上基于 url )添加选项并清除弃用警告,因此验证您传入的连接字符串实际上是否符合新解析器的预期。

                        在未来的版本中,'legacy' 解析器将被删除,然后新的解析器将只是使用的,即使没有该选项。但到那时,预计所有现有代码都有足够的机会根据新解析器的预期测试其现有连接字符串。

                        因此,如果您想在新的驱动程序功能发布时开始使用它们,请使用可用的beta 和后续版本,并且理想情况下,通过启用@987654338 确保您提供对新解析器有效的连接字符串MongoClient.connect() 中的 @ 选项。

                        如果您实际上不需要访问与 MongoDB 4.0 版本预览相关的功能,请将该版本固定到 3.0.x 系列,如前所述。这将按照记录和“固定”工作,这可确保 3.1.x 版本不会“更新”超过预期的依赖关系,直到您真正想要安装稳定版本。

                        【讨论】:

                        • 您是否有更多关于您所说的“被释放到野外”的意思的信息? 3.1.0-beta4是怎么逃出动物园的?你能引用任何关于那个的参考吗?
                        • @Wyck “参考”当然是在提出问题时,做 npm install mongodb 导致 “beta” (在版本字符串中明确标记问题中显示)正在安装,因为它在 npm 存储库中被标记为 stable 而它不应该被安装。这在当时确实是一个错误,因此如果版本字符串中显示alphabeta 的任何代码版本类似地标记为稳定,则应始终予以考虑。自然地,时间已经过去了,这是现在稳定版本中的一个功能,直到(如前所述)它最终会消失。
                        猜你喜欢
                        • 2014-04-30
                        • 1970-01-01
                        • 2020-08-25
                        • 2021-07-02
                        • 2020-01-22
                        • 1970-01-01
                        • 2021-01-09
                        • 2018-03-10
                        相关资源
                        最近更新 更多