'Unable to connect MongoDB server?
I have tried to connect to MongoDB server using the below-mentioned link but I am getting an error, I have entered the correct password and dbName but it couldn't connect. Can you please help me out?
const mongoose = require('mongoose');
mongoose.connect(`mongodb+srv://test:Test@[email protected]/example?retryWrites=true&w=majority`,{userNewUrlParser : true, useUnifiedTopology: true},
err => {
if(!err)
console.log ("'mongoddb connection successed")
else
console.log ('Error white connecting mongodb : ' + JSON.stringify(err, undefined,2))
})
Solution 1:[1]
Use this instead:
mongoose.connect(`mongodb+srv://test:Test@[email protected]/example?retryWrites=true&w=majority`), {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => console.log("---Connected to DB!---"));
Solution 2:[2]
To check if the connection is successful or not, you may use callback functions : on() and once().
const uri = MONGO_URI;
mongoose.connect(uri, { useNewUrlParser: true });
mongoose.connection.on(
'error',
console.error.bind(console, 'connection error: mongodb')
);
mongoose.connection.once('open', () => {
console.log(`mongodb at : ${uri}`);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Onkar Kole |