node js cluster mongoose connection

I am using nodejs built in cluster module in my application mongodb( not sharded) used for storage in each cluster(worker) connection is made using mongoose.createConnection method and closes after inserting data.

But what i am expecting is whenever a request is made it opens connection to the db and process request and close the connection.

But what i noticed that when i checking the mongodb log still open connection and its count sligtly larger than no of processor/(cluster nodes).

and i put poolSize:1,autreconect:false still some connections are not closing even after close() method is called.

my observations are when connection error happends the connection is not closed Please help me

I am using following script to get the connection .

module.exports.getDb = function () {

    var dburl = 'mongodb://localhost/DB';


    db = mongoose.createConnection(dburl, {
        server: {
            socketOptions: {
                keepAlive: 1,
                connectTimeoutMS: 30000
            },
            auto_reconnect: false,
            poolSize: 1

        }

    }, function (err) {

        console.log(err)
    });

    db.on('error', function (err) {
        console.log(err + " this is error");
        db.close();
    });

    return db;

}

and i close the conneciton using db.close() in the end of evey query callback.

Are you looking for something like this?

db.connection.on('error', function (e) {
  console.log(e + " this is error");
  db.close();
});

For my API server, I wrote a plugin for Hapi to handle this. Take a look, it might help you.

'use strict';

var bluebird = require('bluebird');
var mongoose = bluebird.promisifyAll(require('mongoose'));

exports.register = function(plugin, options, next) {

  mongoose.connect(options.mongo.uri, options.mongo.options, function (e) {
    if (e) {
      plugin.log(['error', 'database', 'mongodb'], 'Unable to connect to MongoDB: ' + e.message);
      process.exit();
    }

    mongoose.connection.once('open', function () {
      plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' +  options.mongo.uri);
    });

    mongoose.connection.on('connected', function () {
      plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' +  options.mongo.uri);
    });

    mongoose.connection.on('error', function (e) {
      plugin.log(['error', 'database', 'mongodb'], 'MongoDB ' + e.message);
    });

    mongoose.connection.on('disconnected', function () {
      plugin.log(['warn', 'database', 'mongodb'], 'MongoDB was disconnected');
    });
  });

  return next();
};

exports.register.attributes = {
  name: 'mongoose',
  version: '1.0.0'
};