Search code examples
node.jsmongodbexpressconnection-pooling

One mongo connection in multiple Node modules


I am trying to have all my Node modules share one Mongo connection, and am having trouble doing so. I've looked at some of the materials written about this already. Below is the main file, the Mongo helper file, and another file that tries to use the connection. The trouble is that when the route file tries to use the Mongo connection, db is null.

Mongo helper file:

var mongo = require('mongodb').MongoClient

var _db

function connect(callback) {
    const host = '---'
    const database = '---'
    const user = '---'
    const pass = '---'
    const uri = 'mongodb://' + user + ':' + pass + '@' + host + '/' + database

    mongo.connect(uri, (err, client) => {
        console.log('Connected to Mongo')
        _db = client.db(database)
        return callback(err)
    })
}

function db() {
    return _db;
}

module.exports = {
    connect: connect,
    db: db
}

Main file:

var express = require('express')
var app = express()
var mongo = require('./helpers/mongo')
mongo.connect((err) => {
    if (err !== null) {
        console.log("Error connecting to Mongo: " + err)
        process.exit()
    }
})

var problems = require('./routes/problems.js')
app.use('/problem', problems)

app.listen(3000)

Route file:

var express = require('express')
var router = express.Router()
var db = require('../helpers/mongo').db()

router.get('/stuff', (req, res) => {
    var problems = db.collection('problems')
    res.send('working correctly')
})

module.exports = router

Solution

  • What about mongoose?

    const mongoose = require('mongoose');
    
    // connect to the database (mongodb)
    mongoose.connect('mongodb:<host>/<db>', {useMongoClient: true});
    mongoose.promise = global.Promise;
    var db = mongoose.connection;
    
    // Check for DB connection
    db.once('open', function(){
      console.log('Connected to Mongo Db');
    });
    
    // Check for DB errors
    db.on('error', function(err){
      console.log(err);
    });