162

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.

Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
iLiA
  • 3,053
  • 4
  • 23
  • 45

30 Answers30

270

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.

Saswata
  • 1,290
  • 2
  • 14
  • 28
Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
  • i thought the same (downgrade version), I am using mlab clusters so maybe is the reason why warning does not dissapear? – iLiA Sep 12 '19 at 10:53
  • 3
    there is a bug in latest mongoose `5.7.7` if you use `createConnection()` instead of `connect()`, like `mongoose.createConnection(conString, { useUnifiedTopology: true })`. `useUnifiedTopology` won't be taken in consideration and you will still get the warning. event with `mongoose.set('useUnifiedTopology', true)` i still get the warning. – Louis Grellet Nov 06 '19 at 14:35
  • 2
    Warning still persist after downgrading to 5.6.13 – O'Dane Brissett Apr 03 '20 at 17:23
  • 1
    I'm getting that error using the native MongoDB driver! – Akhila Jul 14 '20 at 22:29
  • Here we have all the deprecated options: https://mongoosejs.com/docs/deprecations.html – Murtaza Ahmad Sep 29 '20 at 08:06
  • This is what worked for me: mongoose.set('useUnifiedTopology', true); mongoose.connect( 'mongo_connection_string', { useNewUrlParser: true }) – Samuel Nwaokoro Nov 11 '20 at 18:41
  • I have Mongoose 5.11.12 with the desired option useUnifiedTopology = true, but the error won't go away. – ivan hertz May 27 '21 at 15:37
35

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 });
tamilselvan s
  • 1,045
  • 2
  • 11
  • 13
  • 14
    if you read my question, i mentioned there that i added `useUnifiedTopology: true` in my configuration and it still shows me warning – iLiA Sep 12 '19 at 10:53
  • 5
    I had this problem and I also add `useUnifiedTopology: true` but still the same message is coming on the console. – RSA Sep 17 '19 at 09:45
  • 7
    For anyone getting the message still, try calling `mongoose.set('useUnifiedTopology', true)` before mongoose.connect. – dev4life Sep 23 '19 at 18:54
  • Yes, this is the right answer. You just have to put "useUnifiedTopology: true, useNewUrlParser: true" together inside a pair of { }. I didn't use "useCreateIndex: true" though, but it gives me some idea. dev4life's way also works. – William Hou Oct 11 '19 at 02:18
  • mongoose .connect("db conn url", { useUnifiedTopology: true, useNewUrlParser: true, }) .then(() => console.log('MongoDB Connected!')) .catch(err => { err => console.log(err) }) this is what worked for me – Sanket Sonavane Dec 27 '19 at 05:20
  • I installed the newer version of a mongoose but the error was still the same. I kept on looking and find out that, it was because of the Network Access. You should allow access from anywhere. Go to the network access and change it to access from anywhere. – sophin May 18 '21 at 12:02
16

This solved my problem.

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

 const client = new MongoClient(url, {useUnifiedTopology: true});
  • thanks for the answer, but this is mongoose question, and i am not using mongoclient – iLiA Nov 19 '19 at 15:22
  • 5
    @iLiA You are welcome. Yes I know. But this answer may be of help to someone, since I found your question exactly by title topic and not by content (and the content of your question is very close to general information about MongoClient) –  Юрий Светлов Nov 19 '19 at 18:08
  • 1
    Thanks for the answer! As mentioned by you I landed up here due the error mentioned while working with mongoclient and not mongoose, helps! – Mugdha Mar 09 '21 at 15:44
5
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.

Hassan Ali Shahzad
  • 2,439
  • 29
  • 32
  • 4
    Also make sure to add `useUnifiedTopology: true` to all the dependencies that uses mongoDB, in my case I was using `wiston-mongodb` I had to add it in the option as well `winston.add(new winston.transports.MongoDB({ db: config.get('db'), options: { useUnifiedTopology: true } }));` – Gael Musi Jan 03 '20 at 13:45
  • @GaelMusikingala this was my problem. Thanks for pointing that out – akmalmzamri Feb 16 '20 at 10:17
  • @GaelMusikingala, Thanks for saving my life. ❤️ – Mr.spShuvo Oct 28 '20 at 13:35
3

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);
    }
};
Niran Yousuf
  • 83
  • 1
  • 9
3

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.

Richard Vergis
  • 1,037
  • 10
  • 20
3

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 node@16.4.0 and mongoose@5.13.1

2

Use the following code to avoid that error

MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true});
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
2

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

mohamad b
  • 81
  • 2
  • 4
1

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

codejockie
  • 9,020
  • 4
  • 40
  • 46
1
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

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.')
    })
licensede
  • 23
  • 4
1

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}`);
});
Clemsang
  • 5,053
  • 3
  • 23
  • 41
  • Please add some explanation to your answer! Also, don't forget to check this: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Prathamesh Koshti Dec 16 '20 at 09:02
1

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();
  });
});
Bhanu Pratap
  • 1,635
  • 17
  • 17
1

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/

X X
  • 81
  • 7
Mugdha
  • 171
  • 2
  • 10
1

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!

ivan hertz
  • 185
  • 1
  • 6
0

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 mongodb-community@4.2
    

    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!

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
0
   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);
    });  

}});

StarDrop9
  • 168
  • 5
0

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();
Sanjay kumar
  • 1,653
  • 12
  • 18
0

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

Steven Ventimiglia
  • 886
  • 1
  • 11
  • 19
0

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

use this line, this worked for me

mongoose.set('useUnifiedTopology', true);
Sunil Sahu
  • 13
  • 1
  • 5
  • 1
    When possible, please make an effort to provide additional explanation instead of just code. Such answers tend to be more useful as they help members of the community and especially new developers better understand the reasoning of the solution, and can help prevent the need to address follow-up questions. – Rajan Jun 13 '20 at 12:27
0

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});
David Buck
  • 3,752
  • 35
  • 31
  • 35
Rohan Devaki
  • 2,931
  • 1
  • 14
  • 22
0
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));
    }
});
kiran r
  • 13
  • 7
  • When possible, please make an effort to provide additional explanation instead of just code. Such answers tend to be more useful as they help members of the community and especially new developers better understand the reasoning of the solution, and can help prevent the need to address follow-up questions. – Rajan Jun 24 '20 at 14:06
0

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});
Dilan
  • 2,610
  • 7
  • 23
  • 33
0

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,
};
Mohammed Al-Reai
  • 2,344
  • 14
  • 18
0

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));
Chamon Roy
  • 731
  • 5
  • 8
0
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 });
AM SHOVON
  • 1
  • 1
0
const mongoose = require('mongoose');
const DB = process.env.DATABASE;
mongoose.connect(DB, {
    useNewUrlParser: true, 
    useCreateIndex: true, 
    useUnifiedTopology: true, 
    useFindAndModify: false
}).then(()=>{ 
    console.log("connection successful");
}).catch((err) =>{
    console.log("no connection");
});
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 06 '22 at 19:05
0

If you are using winston, you need { useUnifiedTopology: true }

for example:

winston.add(
  new winston.transports.MongoDB({
    db: 'mongodb://localhost/vidly',
    level: 'error',
    options: { useUnifiedTopology: true },
  })
);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
qlian1000
  • 15
  • 1