Using Databases in Modules - Express.js Guide: The Comprehensive Book on Express.js (2014)

Express.js Guide: The Comprehensive Book on Express.js (2014)

Using Databases in Modules

With the native Node.js MongoDB driver, the Express.js server needs to wait for the connection to be created before it can use the database:

1 ...

2 var mongodb = require ('mongodb');

3 var Db = mongodb.Db;

4 var db=new Db ('test', new Server(dbHost, dbPort, {}));

5 ...

6 db.open(function(error, dbConnection){

7 var app = express();

8 app.get(...);

9 ...

10 app.listen(3000);

11 });

Thanks to more advanced libraries like Mongoskin, Monk and Mongoose that have buffering, developers’ tasks can be as easy as:

1 var express = require('express'),

2 mongoskin = require('mongoskin');

3

4 var app = express();

5 app.use(express.bodyParser());

6

7 var db = mongoskin.db('localhost:27017/test', {safe:true});

8 ...

9 app.get('/', function(req, res) {

10 res.send('please select a collection, e.g., /collections/messages')

11 });

12 ...

13 app.listen(3000);

In a case when we have routes that need access to database objects, like connection, models, etc. — but those routes aren’t in the main server file — all we need to do is attach the required object to the request, i.e., req:

1 app.use(function(req, res, next) {

2 req.db = db;

3 next();

4 }

Another way is to pass/accept the needed variables into the constructor. The example of the routes.js module:

1 module.exports = function(app){

2 console.log (app.get('db')); //has everything we need!

3 ...

4 return {

5 findUsers: function(req, res) {

6 ...

7 }

8 }

And the main file:

1 var app = express();

2 ...

3 app.set('db',db);

4 routes = require('./routes.js')(app);

5 ...

6 app.get('/users', routes.findUser);

7 ...

Or, we can refactor in a variable:

1 var app = express();

2 ...

3 app.set('db',db);

4 Routes = require('./routes.js');

5 routes = Routes(app);

6 ...

7 app.get('/users', routes.findUser);

8 ...

Readers can try passing data to modules themselves with the example in the expressjsguide/routes folder. For that, simply run $ node -e "require('./routes-module-exports').FindStories('databases');" from the main folder, i.e., expressjsguide.

For a real-life example of passing a Mongoose database object to routes via req object, take a look at the HackHall chapter.