Search code examples
javascriptnode.jsmongodbexpressmonk

How to acess db connection in whole app in node.js?


I connect mongodb with monk in app.js

var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

app.use(function(req,res,next){
  req.db = db;
  next();
});

It working fine here . But now I add index.js in routes folder

var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

exports.index = function(req, res){
  var collection = db.get('usercollection');
  collection.find({},{},function(e,docs){
  res.render('userlist', { "userlist" : docs});
});
res.render('index', { title: 'Express' })
};

It also working fine. But I am connecting DB both in app.js and index.js . Which thing I need to do that connection define in app.js is accessible in index.js


Solution

  • The two solution I know are:

    Put the connection in another file, import that file.

    db.js

    var monk = require('monk');
    module.exports = monk('localhost:27017/nodetest1');
    

    Other files:

    var db = require('./db.js');
    

    Or pass the same connection around:

    app.js:

    var monk = require('monk');
    var db = monk('localhost:27017/nodetest1');
    var module = require('./myModule.js')(db);
    

    myModule.js:

    module.exports = (db) => {
        //...
    };
    

    Or:

    app.js:

    var monk = require('monk');
    var db = monk('localhost:27017/nodetest1');
    var module = require('./myModule.js');
    module.init(db);
    

    myModule.js:

    var db;
    
    exports.init = (masterDb) => {
        db = masterDb;
    };
    

    And ensuring db is set before using it.