Reputation: 11
I am fairly new to node.js.
I am currently using lowdb for my database while I get the app started.
In the index.js file I have:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var request = require('request');
var path = require('path');
var low = require('lowdb');
var db = low('db.json');
var routes = require('./routes');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, '/public')));
app.use('/', routes);
server.listen(3000, function(){
console.log('listening on port 3000');
});
Then in my routes file I have something like:
var express = require('express');
var router = express.Router();
var account = require('./controllers/accounts.js');
router.post('/login', account.login);
router.get('/', function(req, res){
res.render('home');
});
module.exports = router;
And finally in my account controller I have:
exports.login = function(req, res){
var email = req.body.email;
var password = req.body.password;
...
}
The routing to controller system works. However I need to access the lowdb object from all of my routed controller functions (and also possibly elsewhere).
If in app.js I set:
global.db = db;
Then it seems to work, but from what I have read, setting this globally isn't the ideal solution. What is the appropriate way to be able to access the db from the controller files without having to set the db connection in every single file.
Upvotes: 1
Views: 2036
Reputation: 498
It looks like you can probably just setup and use the db
directly in your routes file since you're not actually using the db
in your main file. If it's that simple then I'd opt for doing that:
// routes file
var low = require('lowdb');
var db = low('db.json');
Alternatively, if you need to setup your db
in the main file and pass it into the routes file and/or other modules, instead of exporting the router directly in the routes file, export a function
which takes the db
as input and returns the router
. Then you can pass the db
into the routes module when you require
it.
// routes file
module.exports = function (db) {
// router setup using the input `db`
// ...
return router;
}
// index.js
var low = require('lowdb');
var db = low('db.json');
var routes = require('./routes')(db);
Upvotes: 1
Reputation: 45432
In your index.js
file (application root) store the lowdb
object in your express
object :
var app = express();
var db = low('db.json');
app.db = db;
In your controller (accounts.js
), access your database with req.app.db
:
exports.login = function(req, res){
var email = req.body.email;
var password = req.body.password;
var db = req.app.db;
}
Upvotes: 2