Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing database connection around in a nodejs application

I'm using express 3 in my node application and I've broken my routes into separate files...

app.use('/', routes);
app.use('/users', users);

The problem is that I need a database connection in many of these routes. Should I be connecting to the database in each of the route files or can I connect in my main app file and somehow pass the connection to the includes?


I used express-generator to create a skeleton app. In app.js the routes are included like this...

app.use('/', routes);
app.use('/users', users);

And in each other these files there are routes as follows...

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
    res.render('index');
});
like image 932
michael Avatar asked Sep 04 '14 16:09

michael


People also ask

CAN node JS interact with database?

Node.js can be used in database applications. One of the most popular databases is MySQL.

How do I link multiple databases in node JS?

According to the fine manual, createConnection() can be used to connect to multiple databases. However, you need to create separate models for each connection/database: var conn = mongoose. createConnection('mongodb://localhost/testA'); var conn2 = mongoose.


1 Answers

I simply keep the database connection in the app:

app.set('db',new MyDAO(config)); <-- use where you define your routes.

then, inside the route, in get() or post() I simply do

req.app.get('db').usercollection.find()

This way you keep your database connection pool attached to the gloabl application context.

Alternative common approach is to extend req on every request, but it is executed every time:

app.use(function(req,res,next){
    req.db = db; //this db comes from app.js context where you define it
    next();
});
like image 190
Alex Pakka Avatar answered Oct 23 '22 02:10

Alex Pakka