MongoDB Singleton Connection in Node

What's the best way to setup singleton in Node for Mongodb? I tried the following code but it doesn't work when fast calling a lot of calls.

The singleton is not configured before subsequent calls and therefore it tries to open too many connections and eventually fails. The call below works well for making infrequent calls.

Anyone have any best practice suggestions here?

var db_singleon;

var getConnection= function getConnection(callback)
{
    if (db_singleton)
    { 
      callback(null,db_singleton);
    }
    else
    {
        var connURL = mongoURI; //set in env variables
        mongodb.connect(connURL,function(err,db){
            if(err)
                console.error("Error creating new connection "+err);
            else
            {
                db_singleton=db;    
                console.error("created new connection");
            }
            callback(err,db_singleton);
            return;
        });
    }
}

      

+3


source to share


1 answer


node modules are standalone by themselves, just create a module db

somewhere:

var mongo = require('mongojs');
var config = require('path/to/config');
var connection = mongo.connect(config.connection, config.collections);

module.exports = connection;

      



and then require('path/to/db')

in your models, etc.

+3


source







All Articles