Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose connection events with createConnection

I moved away from using the default connection to a explicitly defined connection.

My code is working except that none of the event handlers which track the state of my mongo connection are firing.

the events used to fire when I was using default mongoose connection. (mongoose.connect).

var mongoose = require('mongoose'),
    logger = require('../logger'),
    config = require('../config');  

mongoose.connection.on('connecting', function(){
    logger.info("trying to establish a connection to mongo");
});

mongoose.connection.on('connected', function() {
    logger.info("connection established successfully");
});

mongoose.connection.on('error', function(err) {
    logger.error('connection to mongo failed ' + err);
});

mongoose.connection.on('disconnected', function() {
    logger.log('mongo db connection closed');
})

var gracefulExit = function() {
    db.close(function(){
        logger.log("mongoose connection with db " + server + 'is closing');
        process.exit(0);
    });
};

process.on('SIGNT', gracefulExit).on('SIGTERM', gracefulExit);

var db = mongoose.createConnection(config.get('DB_URL'));
module.exports = db;

the problem with the code is

  1. None of the event handlers are firing.
  2. Even the process events on SIGNT and SIGTERM are not firing.

I also tried

var db = mongoose.createConnection(config.get('DB_URL'));

db.on('connecting', function(){
    logger.info("trying to establish a connection to mongo");
});

but this also doesn't fire.

like image 464
Knows Not Much Avatar asked Jun 07 '14 18:06

Knows Not Much


2 Answers

i also faced with this problem,
and finally i solved it, after understood that the connect() / createConnection() execute before i declare the event handlers. so the my open or connected events handlers will never called again.

so by declare them first and just after trying to connect - will solve your problem!

for example:

try {
  mongoose.connection
    .on('error', err => {
      console.error(err);
    })
    .on('open', err => {
      console.log(`DB connected`);
    })

  await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
  handleError(error);
}
like image 167
ofir_aghai Avatar answered Nov 07 '22 18:11

ofir_aghai


This snippet blow work fine for me

const connection = mongoose.createConnection(`mongodb://${process.env.MONGO_URI}`);

connection.on('connected', () => {
  console.log('connected to mongodb');
});

connection.on('disconnected', () => {
  console.log('connection disconnected');
});
like image 27
R Rungsikavanich Avatar answered Nov 07 '22 17:11

R Rungsikavanich