erikpalla
4/11/2017 - 3:41 PM

mongodb-connection

mongodb-connection

mongoose.Promise = global.Promise;
const dbURI = cfServ ? cfServ.mongodb[0].credentials.url : 'mongodb://127.0.0.1:27017/stats_test';
const reconnectInterval = 90000; // ms
const maxReconnectTries = 15;
let reconnectTries = 0;
let connectedBefore = false;

const connect = () => {
  mongoose.connect(dbURI, { auto_reconnect: true })
    .then(() => {
      reconnectTries = 0;
      connectedBefore = true;
    })
    .catch(() => { });
};
const db = mongoose.connection;

db.on('connecting', () => {
  logger.info('Connecting to MongoDB...');
});
db.on('error', (error) => {
  logger.error(`MongoDB connection error: ${error}`);
  connectedBefore = false;
  mongoose.disconnect();
});
db.on('connected', () => {
  logger.info('Connected to MongoDB!');
});
db.once('open', () => {
  logger.info('MongoDB connection opened!');
});
db.on('reconnected', () => {
  logger.info('MongoDB reconnected!');
});
db.on('disconnected', () => {
  if (!connectedBefore) {
    if (maxReconnectTries > reconnectTries) {
      logger.error(`MongoDB disconnected! Reconnecting in ${reconnectInterval / 1000}s...`);
      reconnectTries += 1;
      setTimeout(() => connect(), reconnectInterval);
    } else {
      logger.error(`MongoDb disconnected! Max reconnection count (${maxReconnectTries}) reached...`);
      process.exit(1);
    }
  } else {
    logger.info('MongoDb disconnected!');
  }
});
process.on('SIGINT', () => {
  db.close(() => {
    logger.info('MongoDb connection disconnected through app termination');
    process.exit(0);
  });
});

connect();