Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass option { useUnifiedTopology: true } to the MongoClient constructor

Does anyone know why I'm still receiving a deprecation warning even though I've already specified useUnifiedTopoology: true in my MongoClient constructor?

Thank you in advance!

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
}

And I'm getting the following error:

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.

enter image description here

enter image description here

like image 818
Han Avatar asked Apr 17 '20 07:04

Han


People also ask

What is useUnifiedTopology true?

useUnifiedTopology: False by default. Set to true to opt in to using the MongoDB driver's new connection management engine. You should set this option to true , except for the unlikely case that it prevents you from maintaining a stable connection.

What is MongoClient constructor?

Description. MongoClient() Initializes a new instance of the MongoClient class. MongoClient(String) Initializes a new instance of the MongoClient class.

What is a MongoClient object?

MongoClient is the name of a class that you imported from the mongodb package. MongoClient. connect() is a static method of that class. It creates an actual instance of MongoClient (your client object) and passes it to your callback.

What is useCreateIndex?

the useCreateIndex option ensures that you are using the new function calls. Reference: https://mongoosejs.com/docs/connections.html#options https://mongoosejs.com/docs/deprecations.html.


2 Answers

I'm using Mongoose for MongoDB, the same code with no error. mongoose.connect("mongodb://localhost:27017/YOURDB", { useNewUrlParser: true, useUnifiedTopology: true });

like image 62
40Sherrin Avatar answered Oct 13 '22 00:10

40Sherrin


You can do it this way

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...
});
like image 40
Jonel Dominic Brave Avatar answered Oct 12 '22 23:10

Jonel Dominic Brave