How to properly reuse connection to Mongodb across NodeJs application and modules How to properly reuse connection to Mongodb across NodeJs application and modules express express

How to properly reuse connection to Mongodb across NodeJs application and modules


You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:

const MongoClient = require( 'mongodb' ).MongoClient;const url = "mongodb://localhost:27017";var _db;module.exports = {  connectToServer: function( callback ) {    MongoClient.connect( url,  { useNewUrlParser: true }, function( err, client ) {      _db  = client.db('test_db');      return callback( err );    } );  },  getDb: function() {    return _db;  }};

To use it, you would do this in your app.js:

var mongoUtil = require( 'mongoUtil' );mongoUtil.connectToServer( function( err, client ) {  if (err) console.log(err);  // start the rest of your app here} );

And then, when you need access to mongo somewhere else, like in another .js file, you can do this:

var mongoUtil = require( 'mongoUtil' );var db = mongoUtil.getDb();db.collection( 'users' ).find();

The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.

Note, code not tested.


There are many ways this could be tweaked to accept configuration objects in places, but overall it's similar to how you have your code laid out, albeit with more modern JS syntax. Could easily be rewritten to prototypes and callbacks, if that's your requirement.

mongo.js

const { MongoClient } = require('mongodb');const config = require('./config');const Users = require('./Users');const conf = config.get('mongodb');class MongoBot {  constructor() {    const url = `mongodb://${conf.hosts.join(',')}`;    this.client = new MongoClient(url, conf.opts);  }  async init() {    await this.client.connect();    console.log('connected');    this.db = this.client.db(conf.db);    this.Users = new Users(this.db);  }}module.exports = new MongoBot();

Users.js

class User {  constructor(db) {    this.collection = db.collection('users');  }  async addUser(user) {    const newUser = await this.collection.insertOne(user);    return newUser;  }}module.exports = User;

app.js

const mongo = require('./mongo');async function start() {  // other app startup stuff...  await mongo.init();  // other app startup stuff...}start();

someFile.js

const { Users } = require('./mongo');async function someFunction(userInfo) {  const user = await Users.addUser(userInfo);  return user;}


If you are using Express, then you can use mongo-express-req module that allows you to get db connection in request object.

Install

npm install --save mongo-express-req

server.js

var app = require('express')();var mongoExpressReq = require('mongo-express-req');app.use(mongoExpressReq('mongodb://localhost/test'));

routes/users.js

app.get('/', function (req, res, next) {    req.db // => Db object});

Note: mongo-express-req is fork of not maintained express-mongo-db.