7

I am looking for some direction here from some seasoned node.js programmers. The biggest issue I am running into is passing around variables into separate modules. For example in my server.js I have the following:

var db = mongoose.createConnection('localhost','test');

Now I am not running my routes inside of the server.js file they are separated into there own files. So for a blog example it might be like this:

app.get('/blog/post/:id',function(req,res){
    //do something here
}

Now this is where the problem comes in. I do not want to have to setup a database connection in each of my routes and not to mention I would think that it would make a ton of connections. How do I handle this, is there a sample "REAL WORLD" application out there because I cannot seem to find anything about this and I know people have had to have this problem before. I know that node caches the modules but I cant imagine that it would cache the connection given it was in its own module. I created a config module that just holds the site config so requiring this where I need it is not a problem. I imagine there are other things that I am gonna wanna do this with so it would be best to figure this out now.

Any help is appreciated.

3 Answers 3

3

Here's what I do in my real world app.

I have a module named redis (that's the database I'm using). It contains the following code:

var store;

exports.store = store = redis.createClient(config.port, config.url);

So, I can directly access the client, if I need to. I almost never do that. The same module contains code like this:

exports.getData = function(dataID, callback){

    var key = DATA_STORE_PREFIX;

    try{
        store.hget(key, dataID, callback);
    } catch(err){
        callback(err);
    }
}

I use this by including the redis module in one or more route modules and calling it like this:

var db = require('redis');

db.getData('someData', function(err, result){
    console.log(result); // real world code goes here!
});

The node module system takes care of the rest.

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

2 Comments

So my only question about this is does this create a new connection everytime? I actually started doing this already but i want to be sure it doesnt.
It seems to reuse an existing connection, if it has one. If connections are automatically dropped when not used then it will reconnect.
3

One way to do it is to add the connection as a property of an object which will be available to all of the modules that need it. For example in my express app I have something like this in my main app file:

require('./config/database')(app);

and the config/database file looks like:

var mongoose = require('mongoose');

module.exports = function(app) {
  var database = app.get('env');
  var uri = database === 'production' ? 'something...' : 'localhost';
  return app.locals.db = mongoose.createConnection(uri, database);
};

Any modules that need a db connection can then access app.locals.db simply by exporting a function which takes app as an argument (just like above). Of course you'll need to modify this somewhat if you are using something other than express, but the idea remains the same.

3 Comments

Very creative solution but i think that kind of clouds the locals. This is definitely something useful though to pass in data to locals automatically
I think that's what app.locals is there for. I've taken this to an extreme in my current project by recursively auto-loading and assigning all major components of the application to properties of app.locals - e.g. all of my models are in app.locals.models. I like this pattern for two reasons: First, my modules work independently of the file structure, i.e. I don't have to write things like require('../../models/user') all over the place. Second, my shared libraries are available to the views - e.g. if I have an app.locals.lib.urlFor, I can use it in a view as lib.urlFor.
Yeah like i said i think it has its uses (especially for config or utilities) but the db i like being able to just require. Thanks though for the input u made a real valid point about the requires
1

You are using express, I see. Just do:

app.set('db',  mongoose.createConnection('localhost','test'))

Then in any module constructor, make sure to pass the app variable, and you can use app.get('db') to get dbto work.

1 Comment

Thanks for the reply but i think that the other solution fits much better. Then my modules can be more generic and it just seems cleaner.

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.