Answer the question
In order to leave comments, you need to log in
How to reconnect to the database in case of a connection break without restarting the application?
At the moment, everything is quite trivial for me:
// Модуль бд
var mongoose = require('mongoose')
module.exports.connect = () => {
mongoose.connect('mongodb://....',
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
var db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error'))
db.once('open', () => {
console.log('Connection Succeeded')
})
return db
}
// app.js
const mongodb_conn_module = require('./config/mongoConnection')
const db = mongodb_conn_module.connect()
Answer the question
In order to leave comments, you need to log in
Add options to mongoose.connect
reconnectTries: 2, // попытки реконнекта
reconnectInterval: 1000, //каждую секунду
connectTimeoutMS: 2000, // после 2 секунд ожидания соединения пытаться снова или сбрасывать
db.on('reconnected', function(){ console.log('reconnected successfully'});
db.on('reconnectFailed', function (error){
//Что делать если все попытки реконнекта провалились
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question