Monday, 1 February 2016

Reuse MongoDB connection properly in ExpressJS

I created a sample app with express-generator and I created a module with all the connection params./helpers/db.jsvar MongoClient = require('mongodb').MongoClient; var ObjectId = require('mongodb').ObjectID; var url = 'mongodb://localhost:27017/piva'; module.exports.init = function(){ MongoClient.connect(url, function(err, db){ if(!err){ console.log('mongodb connected'); } module.exports.db = db; }); }; If I call require('./helpers/db').init() in the main app.js file and I require the module in one of my routes using/routes/index.jsvar db = require('../helpers/db').db; router.get('/', function (req, res, next) { db.collection('test').... index.render({ title: 'Home page' }, res); }); it does not work since db returns undefined while if I require it inside of router.get it works. I think I should start the connection before the app loads, but I don't know how to handle this.Any hint is highly appreciated!

Submitted February 01, 2016 at 02:31PM by damnko

No comments:

Post a Comment