Mongoose and MongoDB patterns — schema design, validation, indexes, virtuals,
99
99%
Does it follow best practices?
Impact
100%
1.11xAverage score across 5 eval scenarios
Passed
No known issues
A SaaS analytics company is preparing to deploy their Node.js backend to production for the first time. Their current database connection code was written during a hackathon and has several problems: it crashes silently when the database is unreachable, it doesn't clean up connections when the process shuts down (causing connection leaks observed in their cloud provider's monitoring dashboard), and the MongoDB URI is hardcoded in source code which failed their last security review.
The DevOps lead has asked you to rewrite the database connection module before the production deploy. The module should be resilient, observable, and safe for containerized deployments (where the orchestrator sends SIGTERM before stopping a container). The application runs multiple concurrent requests and the connection pool size is an important tuning parameter.
Write a TypeScript file at db.ts that exports a connectDB() async function implementing a production-ready Mongoose connection setup.
The file should also set up any necessary process signal handlers so the application shuts down cleanly. Include any event listeners needed to observe the connection lifecycle in the application logs.