mongodb 如何保持数据库连接数量下降?

e3bfsja2  于 2023-10-16  发布在  Go
关注(0)|答案(3)|浏览(110)

我已经创建了一个免费层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;

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

ovfsdjhp

ovfsdjhp1#

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;
8oomwypt

8oomwypt2#

这是因为每次你调用端点时,都会创建一个新的连接,并且由于你没有使用:

connection.close()

因此,在数据库配置文件中,在connectToMongoDB()下面添加另一个函数closeMongoDBConnection(),如下所示:

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

现在,在你的路由中,在finally()块中的右括号之前调用这个**closeMongoDBConnection()**函数:

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;
oug3syen

oug3syen3#

每次你调用connectToMongoDB(),你都打开了一个到MongoDB的新连接,但在你完成它之后,你并没有关闭它。

选项一:重复使用连接

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

选项二:密切联系

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();
    }
  }
});

相关问题