将 option { useUnifiedTopology: true } 传递给 MongoClient 构造函数

Han*_*Han 11 javascript database mongoose mongodb reactjs

有谁知道为什么即使我已经useUnifiedTopoology: trueMongoClient构造函数中指定了我仍然收到弃用警告?

先感谢您!

const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'connectionurl'
const databaseName = 'db'

const client = new MongoClient(connectionURL, { useNewUrlParser: true, useUnifiedTopology: true});

const insertHandler = async(data, collectionName) => {
  await client.connect().then(async() => {
    const collection = client.db(databaseName).collection(collectionName)
    await collection.insertOne(data)
  }).catch(error => {
    console.log("Failed to insert:", error)
  })
}

module.exports = {
  insertHandler: insertHandler
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

DeprecationWarning: 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.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在此处输入图片说明

Jon*_*ave 10

你可以这样做

var mongoDb = require('mongodb');
var mongoClient = mongoDb.MongoClient;
var serverUrl = "mongodb://127.0.0.1:27017/";
var dbName = "sample_db";

mongoClient.connect(serverUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, db) {
   // Code goes here...
});
Run Code Online (Sandbox Code Playgroud)


小智 6

我正在使用 Mongoose for MongoDB,相同的代码没有错误。 mongoose.connect("mongodb://localhost:27017/YOURDB", { useNewUrlParser: true, useUnifiedTopology: true });