A
A
Andrew2019-11-10 16:54:58
MongoDB
Andrew, 2019-11-10 16:54:58

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()

The code is frankly crappy, but I wrote it a year ago, when I just sat down to master the node and js in general) The
question is how to handle the error event correctly? It happens stably when the connection breaks. Since the base is in the cloud, the probability of a gap is extremely high. Mongoose, it seems, has the keepAlive: true parameter by default, but it does not save something.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Somewhere Intech, 2019-11-10
@AndrewRusinas

Add options to mongoose.connect

reconnectTries: 2, // попытки реконнекта
reconnectInterval: 1000, //каждую секунду
connectTimeoutMS: 2000, // после 2 секунд ожидания соединения пытаться снова или сбрасывать

Then catch events through
db.on('reconnected', function(){ console.log('reconnected successfully'});
db.on('reconnectFailed', function (error){
//Что делать если все попытки реконнекта провалились
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question