我有一个数据库包装类,建立一个连接到一些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"

当前回答

(node:16596) 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. (Use node --trace-deprecation ... to show where the warning was created) (node:16596) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

用法:

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

其他回答

检查你的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 });

这几行代码同样适用于所有其他弃用警告:

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

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

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

如Connection String URI Format中所述,不需要设置端口号。

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

如果用户名或密码有@字符,那么像这样使用它:

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