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

当前回答

const mongoose = require('mongoose');

mongoose
  .connect(connection_string, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log("connected to db");
  });

试着用这个

其他回答

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

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

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

我使用mlab.com作为MongoDB数据库。我将连接字符串分离到一个名为config的不同文件夹,并在文件keys.js中保存连接字符串,这是:

模块导出 = { 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}。

简单地说,你需要做到:

猫鼬。connect(connectionString,{useNewUrlParser: true} / /或 MongoClient。connect(connectionString,{useNewUrlParser: true}

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

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

以下为我的工作 对于猫鼬版本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))

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

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

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

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