简体   繁体   中英

mongoose not connected to mongodb server

Mongoose is not connected to MongoDB server

Made sure password and username is correct

const mongoose = require('mongoose')
mongoose.Promise = global.Promise

const uri ="mongodb+srv://halbr:password@cluster0-t2noa.mongodb.net/test?retryWrites=true&w=majority"

mongoose.connect(uri).then(
    () => {
        console.log('Connect to Mongo');
    },
    err => {
        console.log("Error connecting to Mongo:")
        console.log(err);
    }

);

module.exports = mongoose.connection


Can you please try this sample :

const mongoose = require('mongoose')
mongoose.Promise = global.Promise

async function myDbConnection() {

    const url = 'mongodb+srv://halbr:password@cluster0-t2noa.mongodb.net/test?retryWrites=true&w=majority';

    try {
        let connectionPromise = await mongoose.connect(url, { useNewUrlParser: true });
        if (mongoose.connection) {
            console.log('Connected Successfully')
            global.connectionPromise = connectionPromise;
        } else { global.connectionPromise = null; 
                 console.log('not connected to DB') }
        return connectionPromise;
    } catch (error) {
        console.log('Error connecting to DB ::', error);
    }
}

module.exports = myDbConnection();

Please Verify that you added your public IP in IP Whitelist, for testing you can add wildcard. 0.0.0.0/0 , if it's okay you can try to connect to db through command line of it's not working I recommend to add new user with root role and check connection again.

use admin
 db.createUser(
 {
   user: "admin",
   pwd: "password",
   roles: [ { role: "root", db: "admin" } ]
 }
);
exit;

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