1
votes

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;
1

1 Answers

1
votes

Have a file called database.js. Inside it, put this code:

const mongoose = require("mongoose");

const db = "mongodb://localhost:27017/yourDbName" //Or use atlas url.

const connectDB = async () => {
  try {
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false
    });
    console.log("Mongo db Connected !");
  } catch (err) {
    console.log(err.message);
    //exit process with failure
    process.exit(1);
  }
};

module.exports = connectDB;

In your server.js or index.js:

const connectDB = require("./database.js");