MongoDB Connection Pattern
🎯 Purpose
Establish a reusable MongoDB connection helper that keeps a single shared client across the backend.
📦 Setup
Create src/DB/connection.js to house the singleton connection logic that the rest of the backend reuses:
src/DB/connection.js
import mongoose from 'mongoose';
export default class MongoDBConnection {
static connection;
static async connectIfNot() {
if (this.connection) {
return this.connection;
}
this.connection = await mongoose.connect(process.env.MONGO_DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Add any database scripts (like ensuring indexes or defaults) here if needed.
return this.connection;
}
}🛠️ How It Works
- Single connection guard –
connectIfNotensures Mongoose initializes once per process. Subsequent calls reuse the same client. - Config-driven – All connection details live in environment variables so deployment targets stay configurable.
- Script hook – Keep database automation in one place by dropping required scripts in the marked comment block.
✅ Usage Tips
- Expose
MongoDBConnection.connectIfNot()early in your server bootstrap (API handlers, background jobs, etc.). - Add the necessary database scripts (for example ensuring indexes or inserting required defaults) inside the comment block so everything runs after the connection is ready.
- Keep credentials and host strings in environment variables rather than hard coding them in the helper.
📎 Environment
Set MONGO_DB in your environment variables (.env or deployment platform) with the MongoDB connection string before calling connectIfNot.