Karl
Karl

Reputation: 129

MongoDB native driver connection limit in Node.js

I'm really stressed out of my MongoDB connection code.

I've recently noticed that I have a lot of open connections. Eventually the "connection limit" error is reached (in Linux) and I have to restart everything to get it work.

db.js:

var mongodb = require('mongodb');
var connection = null;

exports.getCollection = function(name, connectionConfig){
 return getConnection(connectionConfig)
    .then(function(conn){
        return conn.collection(name);
    })
    .catch(function(err){
        throw err;
    });
};

function getConnection(configuration){
 return promise(function(deferred){
    configuration = configuration ||        config.envConfig.mongoConnections[0];
    var isMainConnection = configuration === config.envConfig.mongoConnections[0];
    if (isMainConnection && connection){
        return { result: connection, isImediate: true };
    }

    var server = getServer(configuration);
    var db = new mongodb.Db(configuration.name, server, { safe: true, auto_reconnect: true });

    function openConnection(err, c){
        if (err){
            return deferred.reject(err);
        }
        if (isMainConnection){
            connection = c;
        }
        console.log("Db connection opened.");
        c.authenticate(configuration.user, configuration.pass, function (err){
            if (err) {
                c.close();
                return deferred.reject(err);
            }
            return deferred.resolve(c);
        });
        c.on('close', function(){
            console.log("Db connection closed.");
            connection = null;
            return deferred.reject(new Error("Db closed."));
        });
    }

    db.open(openConnection);
    return deferred.promise;
});
}

function getServer(config){
 return new mongodb.Server(config.host, config.port, { auto_reconnect:        true });
}

Can anybody help me?

Upvotes: 0

Views: 916

Answers (1)

ItalyPaleAle
ItalyPaleAle

Reputation: 7316

Looks like you're opening a new connection (which then is not closed) for every request: you don't need to do that.

You should call getConnection() only one, and store the connection handler somewhere to use it in every route. A global variable could work, or add it to your Express application.

PS: you may also want to give Mongoose a try, maybe ;)

Upvotes: 1

Related Questions