137
votes

I am using Mongoose with my Node.js app and this is my configuration:

mongoose.connect(process.env.MONGO_URI, {
   useNewUrlParser: true,
   useUnifiedTopology: true,
   useCreateIndex: true,
   useFindAndModify: false
}).then(()=>{
    console.log(`connection to database established`)
}).catch(err=>{
    console.log(`db error ${err.message}`);
    process.exit(-1)
})

but in the console it still gives me the warning:

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.

What is the problem? I was not using useUnifiedTopology before but now it shows up in the console. I added it to the config but it still gives me this warning, why? I do not even use MongoClient.

Edit

As Felipe Plets answered there was a problem in Mongoose and they fixed this bug in later versions. So you can solve problem by updating mongoose version.

28

28 Answers

246
votes

Update

Mongoose 5.7.1 was release and seems to fix the issue, so setting up the useUnifiedTopology option work as expected.

mongoose.connect(mongoConnectionString, {useNewUrlParser: true, useUnifiedTopology: true});

Original answer

I was facing the same issue and decided to deep dive on Mongoose code: https://github.com/Automattic/mongoose/search?q=useUnifiedTopology&unscoped_q=useUnifiedTopology

Seems to be an option added on version 5.7 of Mongoose and not well documented yet. I could not even find it mentioned in the library history https://github.com/Automattic/mongoose/blob/master/History.md

According to a comment in the code:

  • @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to true to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.

There is also an issue on the project GitHub about this error: https://github.com/Automattic/mongoose/issues/8156

In my case I don't use Mongoose in a replica set or sharded cluster and though the option should be false. But if false it complains the setting should be true. Once is true it still don't work, probably because my database does not run on a replica set or sharded cluster.

I've downgraded to 5.6.13 and my project is back working fine. So the only option I see for now is to downgrade it and wait for the fix to update for a newer version.

32
votes

In mongoDB, they deprecated current server and engine monitoring package, so you need to use new server and engine monitoring package. So you just use

{ useUnifiedTopology:true }

mongoose.connect("paste db link", {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true });
16
votes

This solved my problem.

 const url = 'mongodb://localhost:27017';

 const client = new MongoClient(url, {useUnifiedTopology: true});
5
votes
mongoose.connect('mongodb://localhost:27017/Tododb', { useNewUrlParser: true, useUnifiedTopology: true });

Will remove following errors:-

(node:7481) 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.

(node:7481) 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.

3
votes

You Can Try async await

const connectDB = async () => {
    try {
        await mongoose.connect(<database url>, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        });
        console.log("MongoDB Conected")
    } catch (err) {
        console.error(err.message);
        process.exit(1);
    }
};
2
votes

Add the useUnifiedTopology option and set it to true.

Set other 3 configuration of the mongoose.connect options which will deal with other remaining DeprecationWarning.

This configuration works for me!

const url = 'mongodb://localhost:27017/db_name';
mongoose.connect(
    url, 
    { 
        useNewUrlParser: true, 
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false
    }
)

This will solve 4 DeprecationWarning.

  1. 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.
  2. 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.
  3. Collection.ensureIndex is deprecated. Use createIndexes instead.
  4. DeprecationWarning: Mongoose: findOneAndUpdate() and findOneAndDelete() without the useFindAndModify option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-.

Hope it helps.

2
votes

Use the following code to avoid that error

MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true});
2
votes

If your code includes createConnetion for some reason (In my case I'm using GridFsStorage), try adding the following to your code:

    options: {
        useUnifiedTopology: true,
    }

just after file, like this:

    const storage = new GridFsStorage({
    url: mongodbUrl,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }
                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'uploads'
                };
                resolve(fileInfo);
            });
        });
    },
    options: {
        useUnifiedTopology: true,
    }
})

If your case looks like mine, this will surely solve your issue. Regards

1
votes

This worked for me

For folks using MongoClient try this:

MongoClient.connect(connectionurl, 
  {useUnifiedTopology: true, useNewUrlParser: true},  callback() {

For mongoose:

mongoose.connect(connectionurl, 
         {useUnifiedTopology: true, useNewUrlParser: true}).then(()=>{

Remove other connectionOptions

1
votes
const mongoose = require("mongoose");

mongoose.connect('mongodb://localhost:27017/Edureka',{ useNewUrlParser: true, useUnifiedTopology: true }, (error)=> {
    const connectionStatus = !error ? 'Success': 'Error Connecting to database';
    console.log(connectionStatus);
});
1
votes

This works fine for me, and no more errors.

mongoose
.connect(URL_of_mongodb, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log(`DB Connection Error: ${err}`);
});
1
votes

working sample code for mongo, reference link

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.createCollection("customers", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
  });
});
1
votes

Those who having deprecation warning while using Mongoose with extensions like multer-gridfs-storage.

Since GridFS Storage calls your Mongoose constructor, you can pass the suggested option in the instance creation, to obtain inheritance.

new GridFsStorage({ options: { useUnifiedTopology: true }});

Cheers!

1
votes

Above answers are really helpful in knowing what needs to be done to get rid of the warning. But I did not find the answer to 'why'. One of the answers to Warning on Connecting to MongoDB with a Node server points towards https://github.com/mongodb/node-mongodb-native/releases/tag/v3.2.1. Let me try summarizing it here. For more details you can visit the above link.

With v3.1.0 release, the 2.x driver got deprecated and completely rewritten. The rewrite introduces a new concept of Topology replacing the existing topology concepts like Mongos, ReplSet, and Server etc for better maintainability and traceability. One can enable this functionality by passing the flag useUnifiedTopology. The warning is to encourage users to try it out as soon as possible.

One more useful link which discusses this from NodeJS point of view: https://mongodb.github.io/node-mongodb-native/3.3/reference/unified-topology/

0
votes

I was also facing the same issue:

  1. I made sure to be connected to mongoDB by running the following on the terminal:

    brew services start [email protected]
    

    And I got the output:

    Successfully started `mongodb-community`
    

Instructions for installing mongodb at
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/ or https://www.youtube.com/watch?v=IGIcrMTtjoU

  1. My configuration was as follows:

    mongoose.connect(config.mongo_uri, {
        useUnifiedTopology: true,
        useNewUrlParser: true})
        .then(() => console.log("Connected to Database"))
        .catch(err => console.error("An error has occured", err));
    

Which solved my problem!

0
votes
   const mongo = require('mongodb').MongoClient;

   mongo.connect(process.env.DATABASE,{useUnifiedTopology: true, 
   useNewUrlParser: true}, (err, db) => {
      if(err) {
    console.log('Database error: ' + err);
   } else {
    console.log('Successful database connection');
      auth(app, db)
      routes(app, db)

   app.listen(process.env.PORT || 3000, () => {
      console.log("Listening on port " + process.env.PORT);
    });  

}});

0
votes

Setting mongoose connect useUnifiedTopology: true option

  import mongoose from 'mongoose';

        const server = '127.0.0.1:27017'; // REPLACE WITH YOUR DB SERVER
        const database = 'DBName'; // REPLACE WITH YOUR DB NAME
        class Database {
          constructor() {
            this._connect();
          }
          _connect() {
            mongoose.Promise = global.Promise;
            // * Local DB SERVER *
            mongoose
              .connect(`mongodb://${server}/${database}`, {
                useNewUrlParser: true,
                useCreateIndex: true,
                useUnifiedTopology: true
              })
              .then(
                () => console.log(`mongoose version: ${mongoose.version}`),
                console.log('Database connection successful'),
              )
              .catch(err => console.error('Database connection error', err));   
          }
        }
        module.exports = new Database();
0
votes

I want to add to this thread that it may also have to do with other dependencies.

For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session from version 2.3.0 to 2.2.0.

enter image description here

0
votes

i had the same errors popping up each time and this worked for me

mongoose.connect("mongodb://localhost:27017/${yourDB}", {
    useNewUrlParser: true,
    useUnifiedTopology: true

}, function (err) {
    if (err) {
        console.log(err)
    } else {
        console.log("Database connection successful")
    }
});
0
votes

use this line, this worked for me

mongoose.set('useUnifiedTopology', true);
0
votes

If you are using a MongoDB server then after using connect in the cluster clock on connect and finding the URL, the URL will be somehing like this

<mongodb+srv://Rohan:<password>@cluster0-3kcv6.mongodb.net/<dbname>?retryWrites=true&w=majority>

In this case, don't forget to replace the password with your database password and db name and then use

const client = new MongoClient(url,{useUnifiedTopology:true});
0
votes
mongoose.connect("DBURL", {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true },(err)=>{
    if(!err){
         console.log('MongoDB connection sucess');
        }
    else{ 
        console.log('connection not established :' + JSON.stringify(err,undefined,2));
    }
});
0
votes

It is simple , remove the code that you have used and use the below code :

const url = 'mongodb://localhost:27017';
var dbConn = mongodb.MongoClient.connect(url, {useUnifiedTopology: true});
0
votes

if you used typescript add config to the MongoOptions

const MongoOptions: MongoClientOptions = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

      const client = await MongoClient.connect(url, MongoOptions);

if you not used typescript  
const MongoOptions= {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};
0
votes

This will work:

// Connect to Mongo
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);

mongoose
  .connect(db) // Connection String here
  .then(() => console.log("MongoDB Connected..."))
  .catch(() => console.log(err));
0
votes
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

Cut the upper 2nd line then Just Replace that's line

const client = new MongoClient(url, { useUnifiedTopology: true });
0
votes

Well, recently I was facing the same issue. I went throught this mongoose docs and found the solution.

Update your mongodb connection instance as follows and set useUnifiedTopology separately as follows below -

mongoose.connect(process.env.MONGO_URI, {
   useNewUrlParser: true,
   useCreateIndex: true,
   useFindAndModify: false
}).then(()=>{
    console.log(`connection to database established`)
}).catch(err=>{
    console.log(`db error ${err.message}`);
    process.exit(-1)
});

mongoose.set('useUnifiedTopology', true);

Note: I'm using [email protected] and [email protected]

0
votes

It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.

I attach you my code:

const mongodb = require('mongodb')
    const MongoClient = mongodb.MongoClient

    const connectionURL = 'mongodb://127.0.0.1:27017'
    const databaseName = 'task-manager'

    MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
        if(error) {
            return console.log('Error connecting to the server.')
        }

        console.log('Succesfully connected.')
    })