简体   繁体   中英

MongoDB Atlas connection keeps dropping

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;

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM