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

当前回答

我们用的是:

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

其他回答

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

Express.js、API调用case和发送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()
          },
        )
    })
}

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

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

下面的方法对我有用

const mongoose = require('mongoose');

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

猫鼬版本是5.8.10。

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