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

279

我有一个数据库包装类,它建立到某些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 来消除这些警告呢?这对我很重要,因为脚本应该作为计划任务运行,而这些警告会导致垃圾邮件满天飞。

我正在使用版本为 3.1.0-beta4mongodb 驱动程序,以及相应的 @types/mongodb 包在 3.0.18 中。它们都是使用 npm install 安装的最新版本。

解决方法

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

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

6
这是从 beta 版本中某种方式在周末发布到 npm 上的内容。在 API 确实最终确定之前,不要担心它。你做得很对,安装了一个稳定版本。 - Neil Lunn
1
在MongoDB 3.0.0以上的版本中,只需添加以下代码即可连接数据库: mongoose.connect("mongodb://localhost:portnumber/YourDB", { useNewUrlParser: true }) - Majedur
22个回答

8

更新至ECMAScript 8 / await

MongoDB公司提供的ECMAScript 8演示代码存在错误,因此会出现以下警告。

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
}

7

以下是有关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()
          },
        )
    })
}

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

4
这是我的设置方式。提示信息直到我在几天前更新了npm后才在控制台上显示出来。
.connect有三个参数:URI、选项和错误信息。
mongoose.connect(
    keys.getDbConnectionString(),
    { useNewUrlParser: true },
    err => {
        if (err) 
            throw err;
        console.log(`Successfully connected to database.`);
    }
);

3

我们使用的是:

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.");
});

1
请添加一些说明。 - Mathews Sunny

2
const mongoose = require('mongoose');

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

尝试使用这个。

1
这些代码行对于所有其他弃用警告也起到了作用:
const db = await mongoose.createConnection(url, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);

1
我使用了 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 } 
    


1

我正在使用mongoose 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);

1
这对我非常有效:
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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接