Passing database connection in nodejs application

I use express 3 in my node application and I split 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 connect to the database in each route file, or can I connect in my main application file and somehow transfer the connection to the included ones?


I used the express generator to create a skeletal application. In app.js, routes are included like this ...

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

And in each other of these files there are routes as follows:

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

router.get('/', function(req, res) {
    res.render('index');
});
+4
source share
1 answer

I just support connecting to the database in the application:

app.set('db',new MyDAO(config)); < - , .

get() post()

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

, gloabl.

req , :

app.use(function(req,res,next){
    req.db = db; //this db comes from app.js context where you define it
    next();
});
+13

All Articles