skip to Main Content

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


  1. 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.

    const express = require('express');
    const router = express.Router();
    const { MongoClient } = require('mongodb');
    
    // MongoDB connection string and database name
    const mongoURI = process.env.MONGODB_URI;
    const dbName = process.env.DATABASE_NAME;
    
    // Define an endpoint to fetch restaurant data
    router.get('/restaurants', async (req, res) => {
        const client = new MongoClient(mongoURI);
    
        try {
            // Connect to the MongoDB server
            await client.connect();
    
            // Get the database instance
            const db = client.db(dbName);
    
            // Fetch data
            const restaurants = await db
                .collection('restaurants')
                .find({ registrationStatus: 'Active' })
                .sort({ averageRating: -1, numberOfReviews: -1 })
                .toArray();
    
            console.log('Fetch successful');
    
            // Close the MongoDB client connection when done
            await client.close();
    
            res.json(restaurants);
        } catch (error) {
            console.error(error);
    
            // Close the MongoDB client connection in case of an error
            await client.close();
    
            res.status(500).json({ error: 'Internal server error' });
        }
    });
    
    module.exports = router;
    
       
    
    Login or Signup to reply.
  2. Its because each time you call the endpoint, a new connection is created and its not closed since you are not using:

    connection.close()
    

    So, in your database configuration file add another function closeMongoDBConnection() below connectToMongoDB() like this:

    async function closeMongoDBConnection() {
     try {
       await client.close();
       console.log('MongoDB connection closed');
     } catch (error) {
       console.error('Error closing MongoDB connection:', error);
       throw error;
     }
    }
    
     module.exports = {
       connectToMongoDB,
       closeMongoDBConnection,
    };
    

    Now call this closeMongoDBConnection() function in your route just before the closing parentheses in finally() block:

    const express = require('express');
    const router = express.Router();
    const { connectToMongoDB,closeMongoDBConnection } = 
    require('../../database/database'); 
    
    // 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' });
        }finally {
            if (db)
              closeMongoDBConnection(db); // Close the MongoDB connection
      }
    });
    
    module.exports = router;
    
    Login or Signup to reply.
  3. 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

    let db;
    
    async function connectToMongoDB() {
      if (!db) {
        try {
          await client.connect();
          db = client.db(dbName);
        } catch (error) {
          console.error('MongoDB connection error:', error);
          throw error;
        }
      }
      return db;
    }
    

    Option 2 : Close connection

    router.get('/restaurants', async (req, res) => {
      let db;
      try {
        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' });
      } finally {
        if (db) {
          client.close();
        }
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search