javascript
Database
MongoDB Connection with Retry
Robust MongoDB connection handler with automatic retry logic, connection pooling, and graceful shutdown support.
Apex Logic
0 copies
javascript
const mongoose = require('mongoose');
const MAX_RETRIES = 5;
const RETRY_DELAY = 3000;
async function connectDB(retryCount = 0) {
try {
await mongoose.connect(process.env.MONGO_URI, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
});
console.log('MongoDB connected successfully');
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
mongoose.connection.on('disconnected', () => {
console.warn('MongoDB disconnected. Attempting reconnect...');
});
} catch (err) {
console.error(`MongoDB connection attempt ${retryCount + 1} failed:`, err.message);
if (retryCount < MAX_RETRIES) {
console.log(`Retrying in ${RETRY_DELAY / 1000}s...`);
await new Promise(r => setTimeout(r, RETRY_DELAY));
return connectDB(retryCount + 1);
}
throw new Error('Failed to connect to MongoDB after max retries');
}
}
process.on('SIGINT', async () => {
await mongoose.connection.close();
console.log('MongoDB connection closed gracefully');
process.exit(0);
});
module.exports = connectDB;