mongodb-starter icon indicating copy to clipboard operation
mongodb-starter copied to clipboard

The MongoClient is never closed, is this optional?

Open frouo opened this issue 1 year ago • 8 comments

Hi there,

I'm working on implementing MongoDB into my Next.js project. Thanks for this starter.

I was curious why is the Mongo client never closed anywhere? is client.close() optional even for production?

As far as I understand, there is no need to close in development mode since the module is kept across reloads. But what about production especially when the project is hosted on Vercel (which uses serverless functions)?

Thanks in advance for your help 🙏

import { MongoClient } from 'mongodb';

export default async function handler(req, res) {
  const client = await MongoClient.connect(process.env.MONGODB_URI);
  const db = client.db();

  const collection = db.collection('users');
  const users = await collection.find().toArray();

  await client.close() // <- is this important for production?

  res.status(200).json(users);
}

frouo avatar Apr 03 '23 15:04 frouo