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
.
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.
This question is related to
node.js
mongodb
mongoose
database-connection
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.
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();
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.
findOneAndUpdate()
and findOneAndDelete()
without the useFindAndModify
option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-.Hope it helps.
This solved my problem.
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, {useUnifiedTopology: true});
You Can Try async await
const connectDB = async () => {_x000D_
try {_x000D_
await mongoose.connect(<database url>, {_x000D_
useNewUrlParser: true,_x000D_
useCreateIndex: true,_x000D_
useUnifiedTopology: true,_x000D_
useFindAndModify: false_x000D_
});_x000D_
console.log("MongoDB Conected")_x000D_
} catch (err) {_x000D_
console.error(err.message);_x000D_
process.exit(1);_x000D_
}_x000D_
};
_x000D_
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}`);
});
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();
});
});
Use the following code to avoid that error
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true});
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 [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
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!
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")
}
});
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});
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);
});
}});
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 });
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
use this line, this worked for me
mongoose.set('useUnifiedTopology', true);
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);
});
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});
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,
};
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.
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
.
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));
}
});
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.')
})
_x000D_
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
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));
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 });
Source: Stackoverflow.com