Skip to content

Instantly share code, notes, and snippets.

@howarddierking
Created April 21, 2014 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save howarddierking/11158160 to your computer and use it in GitHub Desktop.
Save howarddierking/11158160 to your computer and use it in GitHub Desktop.
bad mongodb connection management
var dbClient;
var ensureDbClient = function(callback){
if(dbClient){
console.info('ensureDbClient: returning existing client');
return callback(null, dbClient);
} else {
console.info('ensureDbClient: returning NEW client');
MongoClient.connect(mongoConnectionString, mongoConnectionOptions, function(err, db){
if(err){
return callback(err, null);
}
dbClient = db;
callback(null, dbClient);
});
}
};
@howarddierking
Copy link
Author

if I call this from within the same module, it's creating a new client each time

For example, if I call this in a loop, a gazillion connections are being created (until I ultimately run out of connections):

var saveItem = function(obj, callback){
    ensureDbClient(function(err, db){
        if(err) return callback(err, null);
        db.collection(organizationsCollection).insert(obj, {w:1}, callback);
    }); 
};

@glennblock
Copy link

Do you mean you are calling saveItem over and over in a for loop?

@howarddierking
Copy link
Author

yes - and as you mentioned on the phone, the culprit is likely that multiple invocations of this fcn have occurred before the initialization of the connection can happen. Modifying the module now to initialize the connection first...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment