Properly close mongoose's connection once you're done
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Mongoose is an elegant and schema-based solution for modeling data in MongoDB, a NoSQL database that's popular among developers for building modern applications. While connecting to the database is a frequent task, ensuring that the connection is properly closed when your application is done is just as critical. Properly closing a Mongoose connection frees up resources, avoids potential memory leaks, and ensures that your application performs optimally.
Importance of Closing Mongoose Connections
Failing to close a Mongoose connection can lead to several issues:
- Resource Leaks: Open connections consume system and network resources, which can degrade application performance.
- Memory Usage: Unclosed connections contribute to increased memory usage, risking application crashes.
- Database Limitations: MongoDB has a limit on the number of connections it can handle. Leaving connections open unnecessarily may lead to your database not being able to accept new incoming connections.
Technical Steps to Close Mongoose Connection
Using disconnect()
To close a Mongoose connection, you employ the disconnect() method. Below is a simple implementation to open and then close a connection:
Using Async/Await
Mongoose connect() and disconnect() are promise-based, so using async/await enhances code readability.
Event Listeners for Graceful Shutdown
A graceful shutdown ensures that your application does not abruptly terminate connections, risking data corruption or loss.
Handling Node.js Signals
Events like SIGINT (CTRL-C in most environments) and SIGTERM are typically used to trigger shutdown processes.
Handling Uncaught Exceptions
To avoid leaving connections open after uncaught exceptions, catch them and attempt a graceful shutdown.
Key Points Summary
| Key Aspect | Description |
| Resource Management | Frees up system resources, avoids memory leaks |
| Method to Close Connection | disconnect() method |
| Asynchronous Handling | Use async/await for better readability |
| Graceful Shutdown | Handling through Node.js signals like SIGINT/SIGTERM and uncaught exceptions |
Additional Tips
- Connection Pooling: Mongoose supports connection pooling out of the box, reducing the overhead of connecting and disconnecting. Adjust pool size if needed through
poolSizeoption while connecting. - Health Checks: Regularly monitor the number of connections and ensure they do not exceed your database's limit, which can be essential in high-traffic applications.
- Logging: Enable logging to track open and closed connections, assisting in identifying issues early.
By adhering to these practices, you can ensure that your use of Mongoose is efficient, and your MongoDB resources are optimally utilized, minimizing the risk of downtime or performance issues.
Related reading
- Pros and cons of multi-leader vs leaderless replication in databases?
- Provision multiple logical databases with Terraform on AWS RDS cluster instance
- psycopg2 insert multiple rows with one query
- Psycopg2 on Amazon Elastic Beanstalk
- Properties order in Margin
- Pros and cons of async/await
- Publish/Subscribe reliable messaging Redis VS RabbitMQ
- Put data first in Kafka or Database?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.