diff --git a/backend/db/mongoose.js b/backend/db/mongoose.js index 73ef8e1..e7d573f 100644 --- a/backend/db/mongoose.js +++ b/backend/db/mongoose.js @@ -36,8 +36,27 @@ async function connectDB() { } } - console.error('[MongoDB] All connection attempts failed. Backend cannot serve dashboard data.'); - // Do NOT exit — allow health check endpoint to remain available + console.error('[MongoDB] Initial connection attempts failed. Scheduling background reconnect every 10s...'); + // Keep retrying in the background so Docker Swarm container restarts never leave backend permanently disconnected + const timer = setInterval(async () => { + if (mongoose.connection.readyState >= 1) { + clearInterval(timer); + return; + } + try { + console.log('[MongoDB] Background reconnect attempt...'); + await mongoose.connect(MONGODB_URI, { + serverSelectionTimeoutMS: 10000, + connectTimeoutMS: 10000, + }); + console.log('[MongoDB] ✓ Background reconnect succeeded to', MONGODB_URI); + clearInterval(timer); + const { logCapacityStats } = require('./capacityTracker'); + logCapacityStats('[MongoDB]').catch(err => console.warn('[MongoDB] Capacity log failed:', err.message)); + } catch (err) { + console.error(`[MongoDB] ✗ Background reconnect failed: ${err.message}`); + } + }, 10000); } module.exports = connectDB;