node.js 通过将 useNewUrlParser 设置为 true 来避免“当前 URL 字符串解析器已弃用”警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50448272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:48:41  来源:igfitidea点击:

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

node.jsmongodbtypescriptexpressmongoose

提问by Lion

I have a database wrapper class that establishes a connection to some MongoDB instance:

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

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

This gave me a warning:

这给了我一个警告:

(node:4833) 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.

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

The connect()method accepts a MongoClientOptionsinstance as second argument. But it doesn't have a property called useNewUrlParser. I also tried to set those property in the connection string like this: mongodb://127.0.0.1/my-db?useNewUrlParser=truebut it has no effect on those warning.

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

So how can I set useNewUrlParserto remove those warning? This is important to me since the script should run as cron and those warnings result in trash-mail spam.

那么我怎样才能设置useNewUrlParser删除这些警告呢?这对我很重要,因为脚本应该作为 cron 运行,而这些警告会导致垃圾邮件垃圾邮件。

I'm using mongodbdriver in version 3.1.0-beta4with corresponding @types/mongodbpackage in 3.0.18. Both of them are the latest avaliable using npm install.

我使用的mongodb驱动程序版本3.1.0-beta4与相应@types/mongodb的包3.0.18。它们都是使用npm install.

Workaround

解决方法

Using an older version of mongodb driver:

使用旧版本的 mongodb 驱动程序:

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

回答by Abhishek Sinha

Check your mongoversion:

检查您的mongo版本:

mongo --version

If you are using version >= 3.1.0, change your mongoconnection file to ->

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

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

or your mongoose connection file to ->

或者你的猫鼬连接文件到 ->

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

Ideally, it's a version 4 feature, but v3.1.0 and above are supporting it too. Check out MongoDB GitHubfor details.

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

回答by Neil Lunn

As noted the 3.1.0-beta4release of the driver got "released into the wild" a little early by the looks of things. The release is part of work in progress to support newer features in the MongoDB 4.0 upcoming release and make some other API changes.

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

One such change triggering the current warning is the useNewUrlParseroption, due to some changes around how passing the connection URI actually works. More on that later.

触发当前警告的此类更改是useNewUrlParser选项,这是由于传递连接 URI 的实际工作方式发生了一些变化。稍后再谈。

Until things "settle down", it would probably be advisable to "pin"at least to the minor version for 3.0.xreleases:

在事情“安定下来”之前,建议至少“固定”到次要版本以进行3.0.x发布:

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

That should stop the 3.1.xbranch being installed on "fresh" installations to node modules. If you already did install a "latest" release which is the "beta" version, then you should clean up your packages ( and package-lock.json) and make sure you bump that down to a 3.0.xseries release.

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

As for actually using the "new" connection URI options, the main restriction is to actually include the porton the connection string:

至于实际使用“新”连接 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)
  }

})()

That's a more "strict" rule in the new code. The main point being that the current code is essentially part of the "node-native-driver" ( npm mongodb) repository code, and the "new code" actually imports from the mongodb-corelibrary which "underpins" the "public" node driver.

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

The point of the "option" being added is to "ease" the transition by adding the option to new code so the newer parser ( actually based around url) is being used in code adding the option and clearing the deprecation warning, and therefore verifying that your connection strings passed in actually comply with what the new parser is expecting.

添加“选项”的目的是通过向新代码添加选项来“简化”转换,以便url在添加选项和清除弃用警告的代码中使用较新的解析器(实际上基于),从而验证您传入的连接字符串实际上符合新解析器的期望。

In future releases the 'legacy' parser would be removed and then the new parser will simply be what is used even without the option. But by that time, it is expected that all existing code had ample opportunity to test their existing connection strings against what the new parser is expecting.

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

So if you want to start using new driver features as they are released, then use the available betaand subsequent releases and ideally make sure you are providing a connection string which is valid for the new parser by enabling the useNewUrlParseroption in MongoClient.connect().

所以,如果你想开始使用新的驱动程序的功能,因为他们被释放,然后使用可用的beta和后续发行版和理想确保你提供一个连接字符串有效期为通过启用新的解析器useNewUrlParser的选项MongoClient.connect()

If you don't actually need access to features related to preview of the MongoDB 4.0 release, then pin the version to a 3.0.xseries as noted earlier. This will work as documented and "pinning" this ensures that 3.1.xreleases are not "updated" over the expected dependency until you actually want to install a stable version.

如果您实际上不需要访问与 MongoDB 4.0 版本预览相关的功能,则3.0.x如前所述将版本固定到一个系列中。这将按照文档和“固定”工作,这可确保3.1.x在您真正想要安装稳定版本之前,不会在预期的依赖项上“更新”版本。

回答by Narendra Maru

The below highlighted code to the mongoose connection solved the warning for the mongoose driver:

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

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

回答by AAshish jha

There is nothing to change. Pass only in the connect function {useNewUrlParser: true }.

没有什么可以改变的。仅在连接函数中传递{useNewUrlParser: true }

This will work:

这将起作用:

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

回答by KARTHIKEYAN.A

You need to add { useNewUrlParser: true }in the mongoose.connect() method.

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

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

回答by Boris Tralji?

The connection string format must be mongodb://user:password@host:port/db

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

For example:

例如:

MongoClient.connect('mongodb://user:[email protected]:27017/yourDB', { useNewUrlParser: true } )

回答by S J

You just need to set the following things before connecting to the database as below:

您只需要在连接到数据库之前设置以下内容,如下所示:

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');

Also,

还,

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().

回答by techguru

The following works for me

以下对我有用

const mongoose = require('mongoose');

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

The mongooseversion is 5.8.10.

mongoose版本5.8.10

回答by mikemaccana

Updated for ECMAScript 8/ await

针对ECMAScript 8更新/等待

The incorrect ECMAScript 8 demo code MongoDB inc providesalso creates this warning.

MongoDB inc 提供的不正确的ECMAScript 8 演示代码也会产生此警告。

MongoDB provides the following advice, which is incorrect

MongoDB 提供以下建议,不正确

To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

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

Doing this will cause the following error:

这样做会导致以下错误:

TypeError: final argument to executeOperationmust be a callback

类型错误:最后一个参数executeOperation必须是回调

Instead the option must be provided to new MongoClient:

相反,必须将选项提供给new MongoClient

See the code below:

请参阅下面的代码:

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
}

回答by Sam

I don't think you need to add { useNewUrlParser: true }.

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

It's up to you if you want to use the new URL parser already. Eventually the warning will go away when MongoDB switches to their new URL parser.

如果您已经想使用新的 URL 解析器,这取决于您。最终,当 MongoDB 切换到新的 URL 解析器时,警告将消失。

As specified in Connection String URI Format, you don't need to set the port number.

连接字符串 URI 格式中所指定,您无需设置端口号。

Just adding { useNewUrlParser: true }is enough.

只需添加{ useNewUrlParser: true }就足够了。