1

I am trying to reuse MongoDB Connections in NodeJS. I am using Native MongoDB Driver v3.6.6. I have read and used the code from this question,this question and many others like it. My app.js is as follows:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var mongoCon=require('./modules/mongoCon');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var config=require('./config.json');
var app = express();
mongoCon.connectDb(function(db){
  app.use(session({"secret": config["sessionSecret"]}));

  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');

  app.use(logger('dev'));
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));

  app.use('/', indexRouter);
  app.use('/users', usersRouter);

  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    next(createError(404));
  });

  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
  });
})
module.exports = app;

My mongoCon file is as follows:

const MongoClient = require( 'mongodb' ).MongoClient;
const mongoCredentials=require('./../config.json')["mongoCredentials"];
var url;
url = "mongodb://"+mongoCredentials["url"]+":"+mongoCredentials["port"];

var _db;
var client=new MongoClient(url,{ useNewUrlParser: true,useUnifiedTopology: true });

module.exports=
{
  connectDb: async function(func=null){
    await client.connect();
      this._db  = await client.db(mongoCredentials["db"]);
      console.log("Database Connected");
      if(func!=null){
        func(this._db)
      }
      return this._db;
  },
  getDb: async function(func=null){
    if(this._db){
      if(func!=null){
        func(this._db)
      }
      return this._db;
    }
    else{
      await this.connectDb();
      if(func!=null){
        func(this._db)
      }
      return this._db;
    }
  }
}

When I want to reuse the connections I call MongoCon.getDb(). But this opens a new db Connection instead of reusing it. If I remove the check for __db in getDb(), it returns undefined. I am not sure how to solve this.

freeroamer90
  • 379
  • 3
  • 11

2 Answers2

0

Try to export connection instance only instead of connectDb and getDb, You can do something like this:

const { MongoClient } = require( 'mongodb' );
const client = new MongoClient(uri);

const DbConnection = () =>  {

    var db = null;
    var model = null;

    const getDBConnection = async () => {
        try {
            let url = 'mongodb://"+mongoCredentials["url"]+":"+mongoCredentials["port"';
            let db = await client.connect(url, {useNewUrlParser:true, useUnifiedTopology:true});
            return db
        } catch (e) {
            return e;
        }
    }

   const getInstance = async () => {
        try {
            if (db != null) {
                console.log(" db connection is already alive");
                return db;
            } else {
                console.log('getting new connection');
                db = await getDBConnection();
                return db;
            }
        } catch (e) {
            return e;
        }
    }

    return getInstance;
}

export default {db: DbConnection()}

In the files you import:

const dbConnection = require('path to file');

const dbInstance =  async() => {
   const db = await dbConnection();
}

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
0

use mongoose and export connection from mongoose and shared between files

const mongoose = require("mongoose");
exports.isReady = false;
exports.connection = null;

mongoose.connect(config.mDB.serverUrl, { useFindAndModify: false, useUnifiedTopology: true, useNewUrlParser: true })
    .then(function (res) {
        
        // console.log('Succeeded connected to: ' + config.mDB.serverUrl);
        exports.isReady = true;
        exports.connection = res;
        exports.con = res.connection
    })

    .catch(function (err) {
       
        // console.error(err)
        // console.log('ERROR connecting to: ' + config.mDB.serverUrl, + '. ' + err);
    })

in another file import this as DB

var DB = require('./DB')
DB.con.collection('test').findAll({}).toArray()
mohammad Naimi
  • 2,259
  • 1
  • 5
  • 15