我有一个数据库包装类,建立一个连接到一些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,但它对那些警告没有影响。

那么我怎么能设置useneurlparser删除这些警告?这对我来说很重要,因为脚本应该以cron的方式运行,而这些警告会导致垃圾邮件。

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

解决方案

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

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

当前回答

我使用的是猫鼬版本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);

其他回答

我是这么说的。直到几天前我更新了npm,这个提示才在我的控制台显示出来。

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

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

没有什么可以改变的。只在连接函数中传递{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();
        }
    })

检查你的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。

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

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

你需要在猫鼬.connect()方法中添加{useNewUrlParser: true}。

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