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

其他回答

连接字符串格式为mongodb://user:password@host:port/db

例如:

MongoClient.connect('mongodb://user:password@127.0.0.1:27017/yourDB', { useNewUrlParser: true } )

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

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

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

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()
          },
        )
    })
}