lundi 20 avril 2015

Singleton MongoDB connection in Node

What is the best way to set up a singleton in Node for Mongodb? I tried the following code, but it does not work when making a lot of calls rapidly.

The singleton does not get set up before subsequent calls, and thus it tries opening too many connections and eventually fails. The below call works well for making infrequent calls.

Anyone have suggestions on the best practice 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;
        });
    }
}

Aucun commentaire:

Enregistrer un commentaire