From b6c3334a560aad922d8d4ba0f18e0db69bd97a24 Mon Sep 17 00:00:00 2001 From: renatocfrancisco Date: Wed, 5 Jul 2023 20:50:47 -0300 Subject: [PATCH] =?UTF-8?q?refactor:=20:recycle:=20fun=C3=A7=C3=A3o=20mong?= =?UTF-8?q?oose=20connect=20em=20db.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 9 --------- config/db.js | 22 +++++++++++++++++++--- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/app.js b/app.js index 0a854da..f70ab6e 100644 --- a/app.js +++ b/app.js @@ -11,15 +11,6 @@ const routes = require('./routes/index') const user = require('./routes/user') const task = require('./routes/task') -db.on('error', console.error.bind(console, 'MongoDB connection error:')) -db.once('open', () => { - console.log('Successful MongoDB connection!') -}) -db.on('disconnected', () => { - console.log('MongoDB disconnected! Reconnecting...') - db.connect(process.env.MONGO_URI) -}) - const app = express() app.use(helmet(), cors(), compression(), morgan('dev'), express.json()) diff --git a/config/db.js b/config/db.js index c457178..e6c2be0 100644 --- a/config/db.js +++ b/config/db.js @@ -1,8 +1,24 @@ const mongoose = require('mongoose') require('dotenv').config() -mongoose.connect(process.env.MONGO_URI) +const connect = () => { + mongoose.connect(process.env.MONGO_URI, { + useNewUrlParser: true, + useUnifiedTopology: true, + serverSelectionTimeoutMS: 5000 + }) + .then(() => console.log('Successful MongoDB connection!')) + .catch((err) => { + console.log('MongoDB connection error: ', err) + setTimeout(connect, 5000) + }) +} -const db = mongoose.connection +mongoose.connection.on('disconnected', () => { + console.log('MongoDB disconnected! Reconnecting...') + setTimeout(connect, 5000) +}) -module.exports = { db } +connect() + +module.exports = { db: mongoose.connection }