import mongoose from 'mongoose'; import User from '../models/UserModel.js'; import Invoice from '../models/InvoiceModel.js'; export const dbConnection = async () => { try { // Enhanced connection options for high concurrency and stability await mongoose.connect(process.env.DB_URL, { // Connection pooling - allows multiple concurrent connections maxPoolSize: 100, // Maximum number of concurrent connections (increased from default 10) minPoolSize: 20, // Minimum number of connections to maintain maxIdleTimeMS: 45000, // Close idle connections after 45 seconds socketTimeoutMS: 60000, // Socket timeout for operations connectTimeoutMS: 10000, // Initial connection timeout serverSelectionTimeoutMS: 10000, // Server selection timeout family: 4, // Use IPv4 // Retries and failover retryWrites: true, // Enable retry writes for transactional consistency retryReads: true, // Enable retry reads for resilience maxStalenessSeconds: 10, // Connection monitoring monitorCommands: false, // Disable command monitoring to reduce overhead }); // Sync indexes for all models and clean up bad indexes await User.syncIndexes(); // Clean up bad indexes on Invoice try { const invoiceCollection = mongoose.connection.collection('invoices'); const indexes = await invoiceCollection.getIndexes(); // Drop the problematic unique index on customer if it exists for (const [indexName, indexSpec] of Object.entries(indexes)) { if (indexName === 'customer_1' && indexSpec.unique) { console.log('Dropping conflicting unique index on customer field...'); await invoiceCollection.dropIndex(indexName); } } } catch (indexErr) { console.warn('Index cleanup warning:', indexErr.message); } await Invoice.syncIndexes(); // Connection event handlers for monitoring mongoose.connection.on('error', (err) => { console.error('MongoDB Connection Error:', err); }); mongoose.connection.on('disconnected', () => { console.warn('MongoDB Disconnected - attempting reconnect'); }); mongoose.connection.on('reconnected', () => { console.log('MongoDB Reconnected Successfully'); }); console.log('Connected To DB Successfully!'); console.log(`Using connection pool size: 20-100`); } catch (err) { console.error('DB Connection Failed:', err.message); // Retry connection after 5 seconds setTimeout(() => { console.log('Retrying database connection...'); dbConnection(); }, 5000); } };