1

My app.js looks below. mogoDBUtils.getMogoDbCon(); will open a db connection when new request comes in. I want to close the DB connection as soon as the api call to route.js is over.

Where do i need to place the code in app.js to close MongoDB connection in the below code so that upon evey new hit it opens a connection and close the connection after api call is completed.

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.disable('x-powered-by')
var mogoDBUtils = require('./controller/utilities/mongodbutils.js')
var logger = require('./controller/utilities/logger.js'); //initialize logger class

require('./routes/route.js')(app); //define express router for api calls
mogoDBUtils.getMogoDbCon(); //open dbconnection

//setup server
var port = process.env.PORT || 80 // port

app.use(express.static('./views/webcontent/', { index: 'index.html' }))//define home page

app.listen(port);
console.log('Listening on port ' + port + '..');

// DB functions

module.exports.getMogoDbCon = function() {
  new Promise((resolve, reject) => {
    var mongoUri = getmongouri(); 
    mongoose.connection.openUri(mongoUri);
    var db = mongoose.connection;

    db.on('error', function () {
      throw new Error('unable to connect to database');
    });    
    return resolve(db); 
  });
}; 

module.exports.closeMongoDBConnection = function () {
  new Promise((resolve, reject) => {
    mongoose.disconnect();
    return resolve(true);
  });
};
alexmac
  • 19,087
  • 7
  • 58
  • 69
Sona Shetty
  • 997
  • 3
  • 18
  • 41

1 Answers1

0

You can do it in a middleware. If you want to open and close connection on each request, you need to create two middlewares: for opening connection and for closing it:

I suppose that getMogoDbCon() and closeMogoDbCon return a promise, otherwise use callbacks.

app.use((req, res, next) => {
  mogoDBUtils
    .getMogoDbCon()
    .then(conn => {
       req.conn = conn;
       next();
     })
    .catch(next);
});

require('./routes/route.js')(app); // define express router for api calls

app.use((req, res, next) => {
  mogoDBUtils
    .closeMogoDbCon(req.conn)
    .then((() => next())
    .catch(next);
});

Note about middleware order declaration. The middleware which opens connection must be defined firstly, after that all your routes, and the last one - the middleware which closes connection.

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • i have added getMogoDbCon() and closeMogoDbCon used in the code in the question.I get an error TypeError: Cannot read property 'then' of undefined in the second middleware to close the connection.Could you please assist. – Sona Shetty Sep 14 '17 at 18:56
  • In both functions add `return` statement: `return new Promise(...` – alexmac Sep 14 '17 at 19:00
  • Connection is not getting closed.Not sure whats wrong with my code – Sona Shetty Sep 14 '17 at 19:25
  • `mongoose.connection.openUri` returns connection object, you *must* use it to close connection: `conn.close()`. I've updated my answer, now I store connection in `req` object and pass it to `closeMogoDbCon` when need to close connection. – alexmac Sep 14 '17 at 19:32