3

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;
        });
    }
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked. I modified it a bit (i.e. I'm not currently using a config file), but the principle of this was exactly what I needed. Thanks @Kosmetika for the pattern!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.