I've integrated MongoDB atlas to my nodejs application, but the connection keeps dropping every few hours, which is forcing the app to restart. Is there a away to handle reconnections in the code to avoid restart of the app ?
{ MongoNetworkError: connection 2 to 67.156.445.93:27017 closed at (anonymous function).forEach.op (/home/ubuntu/app/node_modules/mongodb/lib/cmap/connection.js:63:15) at Map.forEach () at TLSSocket.Connection.stream.on (/home/ubuntu/app/node_modules/mongodb/lib/cmap/connection.js:62:20) at TLSSocket.emit (events.js:203:15) at _handle.close (net.js:607:12) at TCP.done (_tls_wrap.js:388:7) name: 'MongoNetworkError', [Symbol(mongoErrorContextSymbol)]: { isGetMore: true } }
Code:
const log = console.log;
const mongoose = require('mongoose');
const link = ' URL of MONGOATLAS DB';
const connectDB = async () => {
mongoose.connect(link, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected',() => {
log(`MongoDB connection successful!`);
});
mongoose.connection.on('error',(err) => {
log(`MongoDB connection error => ${err}!`);
});
mongoose.connection.on('disconnected', () => {
log(`MongoDB connection diconnected`);
});
}
module.exports = connectDB;