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?