From a75c4bdec15971fd6f559e6bf4b24a90c3a55d2b Mon Sep 17 00:00:00 2001 From: Yoga Pratama Date: Mon, 9 Nov 2026 11:21:29 +0700 Subject: [PATCH] Fix: keep retrying MongoDB connection in background if initial attempts fail --- backend/db/mongoose.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) 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;