Spaces:
Sleeping
Sleeping
File size: 2,861 Bytes
0159174 4dbde5b 0159174 4dbde5b 0159174 4dbde5b 0159174 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | 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);
}
};
|