node.js passing variables node.js passing variables database database

node.js passing variables


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.


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.


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.