Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        });
    }
}
like image 343
Bob Aleena Avatar asked Nov 23 '25 04:11

Bob Aleena


1 Answers

node modules are singletons by theirselves, just make db module 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') it in your models, etc.

like image 59
Kosmetika Avatar answered Nov 24 '25 18:11

Kosmetika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!