如何减少数据库连接量?

问题描述 投票:0回答:1

我创建了一个免费层 MongoDB 集群,并且我从 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.

我的数据库配置如下所示:

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,
};

然后我就有了这个路由器:

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;

是因为我使用后没有再次关闭连接,还是这里的问题到底是什么以及如何解决?

mongodb react-native routes database-connection
1个回答
0
投票

M0集群有连接限制,需要显式关闭以阻止其蔓延。我修改了你的代码并使用了 client.close(),希望能解决问题。

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;

   
© www.soinside.com 2019 - 2024. All rights reserved.