I’m using ExpressJs with Node.js and have put all my routes into a ‘routes’ folder.
On the server, I do my DB connection, then define my routes, like this:
var routes = require('./routes');
var db;
dbconnect = new mongo.Db(config.mongo_database, new mongo.Server(config.mongo_host, config.mongo_port, {}), {});
dbconnect.open(function (err, db) {
db.authenticate(config.mongo_user, config.mongo_pass, function (err, success) {
if (success) {
//routes/index.js
app.get('/', routes.index);
//routes/users.js
app.get('/users', routes.users);
}
});
});
I want to access the ‘db’ object inside each of these routes javascript files. How would I pass that from this ‘app.js’ file to the index.js or users.js?
Thank you!
One suggestion is to expose your routes via a function which accepts a
dbparameter:routes.js:
Wrapping values in a closure like this and returning an object with more functions is a useful pattern, sometimes called “Revealing Module Pattern”. It shows the dependencies clearly, allowing for easy testing (using e.g. a mock db object) while still using a flexible functional approach.