Skip to content
This repository has been archived by the owner on Oct 16, 2023. It is now read-only.

Commit

Permalink
refactor: ♻️ função mongoose connect em db.js
Browse files Browse the repository at this point in the history
  • Loading branch information
renatocfrancisco committed Jul 5, 2023
1 parent 58fa41f commit b6c3334
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
9 changes: 0 additions & 9 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
22 changes: 19 additions & 3 deletions config/db.js
Original file line number Diff line number Diff line change
@@ -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 }

0 comments on commit b6c3334

Please sign in to comment.