Best place to define a connection uri using Express

I have just started learning ExpressJs and I am trying to use it with mongoskin. What I want to know is where is the best place to define the uri to connect to the database. I don't want to do that in every file that needs to connect to the db.

I tried doing this in my app.js file:

var app = express();
...
app.set('db_uri', process.env.NODE_DB || ""localhost/test"");
...
module.exports = app;

And inside the file that would be accessing the db:

var mongo = require('mongoskin'),
    app = require('./../../app'),
    db = mongo.db(app.settings.db_uri);

But the problem is that I always receive an empty object for app. So, I have two questions.

1) Is this the best way to do it?

2) What is wrong that I can't access app?

I think one way of doing it is creating a module that handles the interaction with the database, so you could:

  • write the url there
  • or in a configuration file required in it
  • or you could just use process.env

and require the model when you need database interaction, this way there's no need for express to know about it.

About app not being required: check that you are exporting it via module.exports and that the path is correct (the first ./ could be omitted for example).