node.js - Why is error coming while using mongoose connection? - TagMerge
4Why is error coming while using mongoose connection?Why is error coming while using mongoose connection?

Why is error coming while using mongoose connection?

Asked 5 months ago
0
4 answers

change

mongodb://localhost:270717

into

mongodb://localhost:27017

Source: link

0

var server = tunnel(config, function (error, server) {
if(error){
    console.log("SSH connection error: " + error);
}

mongoose.connect('mongodb://127.0.0.1:27017/mysuperdb');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
    console.log("DB connection successful");
});
I got it all working however i can’t remember exactly what I did however from what i briefly remember it was something around the port numbers. I think i had them mixed up. My final config var looks slightly different to what I have above - it’s currently like:
var config = {
      username : 'xxxxxxx',
      host: 'xxx.xxx.xxx.xxx',
      port:22,
      privateKey:require('fs').readFileSync('id_rsa'),
      dstPort:2xxx7,
      localPort: 2xxx0
  };

Source: link

0

const mongoose = require('mongoose');

const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true
        });

        console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
    } catch (err) {
        console.log(`Error: ${err.message}`.red);
        process.exit(1);
    }

}

module.exports = connectDB;

Source: link

0

Example:
mongoose.connect('mongodb://127.0.0.2/test') // if error it will throw async error
    .then(() => { // if all is ok we will be here
        return server.start();
    })
    .catch(err => { // we will not be here...
        console.error('App starting error:', err.stack);
        process.exit(1);
    });
Workaround:
mongoose.connect('mongodb://127.0.0.2/test', function() { /* dummy function */ })
    .then(() => {
        return server.start();
    })
    .catch(err => { // mongoose connection error will be handled here
        console.error('App starting error:', err.stack);
        process.exit(1);
    });
I think mongoose.connect() throws async error instead of return rejected promise in order to not break backward compatibility. Users expect that application will be finished with error code if something went wrong with mongoose connection establishment. If mongoose.connect() returns rejected promise application will be finished with 0 code and nothing will be output to console. So it will be good to have some way to say mongoose.connect() to return promise. Maybe something like exec():
mongoose.connect('mongodb://127.0.0.2/test').exec()
    .then(() => { // if all is ok we will be here
        return server.start();
    })
    .catch(err => { // if error we will be here
        console.error('App starting error:', err.stack);
        process.exit(1);
    });
mongoose.connect('mongodb://localhost/dbCollection', function(err, db) {
    if (err) {
        console.log('Unable to connect to the server. Please start the server. Error:', err);
    } else {
        console.log('Connected to Server successfully!');
    }
});
Use the callback of mongoose.connect to catch any error during the connection. You can start you server in the event open.
mongoose.connection.once('open', function() {
            logger.info('MongoDB event open');
            logger.debug('MongoDB connected [%s]', url);

            mongoose.connection.on('connected', function() {
                logger.info('MongoDB event connected');
            });

            mongoose.connection.on('disconnected', function() {
                logger.warn('MongoDB event disconnected');
            });

            mongoose.connection.on('reconnected', function() {
                logger.info('MongoDB event reconnected');
            });

            mongoose.connection.on('error', function(err) {
                logger.error('MongoDB event error: ' + err);
            });

            // return resolve();
            return server.start();
        });

        return mongoose.connect(url, options, function(err) {
            if (err) {
                logger.error('MongoDB connection error: ' + err);
                // return reject(err);
                process.exit(1);
            }
        });

Source: link

Recent Questions on node.js

    Programming Languages