I am using MongoDB Atlas M2 tier and I see that I'm given a max of 500 connections for the M2 tier. What is the best way to manage the connections if I have 700 users? Should I close the connection after each query? If so, how should I close the connection after each query? Many thanks in advance and I greatly appreciate any helps
These are the code I have for the NodeJS application and with express API.
dbconfig.js
const mongoose = require('mongoose');
const connectDB = async () => {
try{
const conn = await mongoose.connect(process.env.MONGODB_ATLAS_CONNECTION_STRING,{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true,
useFindAndModify:false})
console.log(`mongodb atlas connected: ${conn.connection.host}`)
}
catch(err){
console.log(err)
process.exit(1)
}
}
module.exports = connectDB
server.js
const express = require("express");
const app = express();
const morgan = require('morgan');
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require('dotenv');
const connectDB = require("./dbconfig/dbconfig");
const cookieParser = require('cookie-parser');
const contactRoute = require('./routes/contact')
dotenv.config()
connectDB()
app.use(cors());
app.use(cookieParser())
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use('/api', contactRoute)
app.listen(port, () => {
console.log(`Listening to part ${port}...`)
})
contact.js
router.post('/contact/allcontact', async (req, res) => {
try {
const contact = await Contact.find()
res.json(contact)
} catch (error) {
res.json({ message: error })
}
})
router.post('/contact/searchcontact', async (req, res) => {
try {
const contact = await Contact.find({ $and: [{ userid: req.body.id }, { contactname: { '$regex': sanitize(req.body.searchData), '$options': 'i' } }] })
res.json(contact)
} catch (error) {
res.json({ message: error })
}
})