Skip to content

The MongoClient is never closed, is this optional? #24

@frouo

Description

@frouo

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions