简体   繁体   中英

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@123@cluster0.cvbne.mongodb.net/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))
    })

Use this instead:

mongoose.connect(`mongodb+srv://test:Test@123@cluster0.cvbne.mongodb.net/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!---"));

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}`);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM