Server Discovery And Monitoring engine is deprecated
Javascriptnode.jsTypescriptMongodbMongooseJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
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 });
Solution 3 - Javascript
This solved my problem.
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, {useUnifiedTopology: true});
Solution 4 - Javascript
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.
Solution 5 - Javascript
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);
}
};
Solution 6 - Javascript
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.
- 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.
- 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.
- Collection.ensureIndex is deprecated. Use createIndexes instead.
- DeprecationWarning: Mongoose:
findOneAndUpdate()
andfindOneAndDelete()
without theuseFindAndModify
option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-.
Hope it helps.
Solution 7 - Javascript
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]
Solution 8 - Javascript
Use the following code to avoid that error
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true});
Solution 9 - Javascript
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
Solution 10 - Javascript
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
Solution 11 - Javascript
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);
});
Solution 12 - Javascript
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}`);
});
Solution 13 - Javascript
> 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();
});
});
Solution 14 - Javascript
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 https://stackoverflow.com/questions/57546635/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/
Solution 15 - Javascript
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!
Solution 16 - Javascript
I was also facing the same issue:
-
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
-
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!
Solution 17 - Javascript
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);
});
}});
Solution 18 - Javascript
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();
Solution 19 - Javascript
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
.
Solution 20 - Javascript
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")
}
});
Solution 21 - Javascript
use this line, this worked for me
mongoose.set('useUnifiedTopology', true);
Solution 22 - Javascript
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});
Solution 23 - Javascript
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));
}
});
Solution 24 - Javascript
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});
Solution 25 - Javascript
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,
};
Solution 26 - Javascript
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.')
})
Solution 27 - Javascript
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));
Solution 28 - Javascript
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 });
Solution 29 - Javascript
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");
});