Database Connections
Node.js applications should manage database connections efficiently. Creating a new database connection for every request is usually expensive. Database clients commonly maintain a connection pool or reusable connection state.
Connection configuration should come from environment variables or secure configuration management.
MongoDB Connection with Mongoose
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGODB_URI);
console.log('MongoDB connected');💡 The database URI is read from the environment and Mongoose establishes a reusable database connection.
Key Takeaways
- Reuse database connections instead of reconnecting per request.
- Keep credentials outside source code.
- Handle connection failures and shutdowns explicitly.
Knowledge Check
Where should a production MongoDB connection string normally be stored?