I’ve created a free tier MongoDB cluster, and I’m getting this message from MongoDB:
You are receiving this alert email because connections to your cluster(s) have exceeded 500, and is nearing the connection limit for the M0 cluster HSDevCluster in the Project Halal Spisesteder Development within Organization YouBen. Please restart your application or login to your Atlas account to see some suggested solutions.
My database configuration look like this:
const { MongoClient } = require('mongodb');
// MongoDB connection string
const mongoURI = process.env.MONGODB_URI;
const dbName = process.env.DATABASE_NAME;
// Create a new MongoClient instance
const client = new MongoClient(mongoURI);
async function connectToMongoDB() {
try {
// Connect to the MongoDB server
await client.connect();
// Get the database instance
const db = client.db(dbName);
return db;
} catch (error) {
console.error('MongoDB connection error:', error);
throw error;
}
}
module.exports = {
connectToMongoDB,
};
Then I have this router:
const express = require('express');
const router = express.Router();
const { connectToMongoDB } = require('../../database/database'); // Import the MongoDB
connection function
// Define an endpoint to fetch restaurant data
router.get('/restaurants', async (req, res) => {
try {
const db = await connectToMongoDB();
const restaurants = await db
.collection('restaurants')
.find({ registrationStatus: "Active" })
.sort({ averageRating: -1, numberOfReviews: -1 })
.toArray();
console.log("fetch successful");
res.json(restaurants);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
Is it because I don’t close the connections again after I use them or what exactly is the issue here and how do I solve this?
3
Answers
The M0 cluster has a connection limit And you need to explicitly close to stop it creeping up. I’ve modified your code and used a client.close(), whi hopefully will solve the problem.
Its because each time you call the endpoint, a new connection is created and its not closed since you are not using:
So, in your database configuration file add another function closeMongoDBConnection() below connectToMongoDB() like this:
Now call this closeMongoDBConnection() function in your route just before the closing parentheses in finally() block:
Each time you call connectToMongoDB() you’re opening a new connection to MongoDB but you’re not closing it after you’re done with it.
Option 1 : Reuse connection
Option 2 : Close connection