2

I am using MongoDB in my NodeJS project with ExpressJS. and the mongoDB npm dependency. The strange thing is that it opens a new connection every time when doing a POST or GET request, and after a few times I am getting the following error:

Connections % of configured limit has gone above 80

Opening the connection like so:

const mongodb = require ('mongodb');

module.exports = {
  dbConn: async function(table) { 
    const client = await mongodb.MongoClient.connect
    ('mongodb+srv://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx.mongodb.net/test?retryWrites=true', {
      useNewUrlParser: true
    });

    return client.db('test').collection(table);
  }
}

Doing a GET or POST request:

const db = require('./db');

router.get('/:id', async (req, res) => {
  try{ 
    const keywords = await db.dbConn('kw_data');
    data = await keywords.findOne({hash: req.params.id});
    if(data != null){
      res.status(200).send(data);
    }
    else{
      res.status(200).send({"result": false});
    }
  }
  catch(e){
    res.status(400).send(e);
    res.status(404).send(e);
    res.status(500).send(e); 
  }
})

Is it so that I can close the connection somehow or just leave it open?

Jan
  • 653
  • 1
  • 7
  • 22
  • 2
    You should be calling `mongodb.MongoClient.connect` once, not each request. – JohnnyHK Apr 17 '19 at 19:54
  • Thanks for pointing the right direction, how can I check if a connection is open and what do I need to call then instead? – Jan Apr 17 '19 at 19:58
  • See https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application – JohnnyHK Apr 17 '19 at 20:10
  • also https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module – 1565986223 Apr 18 '19 at 06:35

0 Answers0