I have a nodejs app which uses mongodb and runs on k8s . But I am getting a problem whenever I change mogodb address, the k8s pod hangs and I've to restart to the pod to make it work again. So I think it happens because node service crashes at that time. How can I write my code to connect to mongodb in a way that the nodejs app doesn't crash when it fails to connect to mongodb or mondodb is down or something happens there. My current code is
exports.connect = function() {
return MongoClient.connect(mongourl);
};
so, you want if mongo connection fails. it should not crash the app. you can juust handle the error
callback and do whatever you want. in my case, i'm re connecting the DB, if its failing. like below:
var mongoose = require('mongoose');
var connection = mongoose.connection;
connection
.on('error', function (err) {
console.log("Error in MongoDB Connection");
console.error(err);
})
.on('disconnected', reConnect)
.once('open', listen);
connection.on('reconnected', function () {
console.log('MongoDB reconnected!');
});
function connect() {
const connection = mongoose.connect(<mongo Uri here >, <connection options>,(err)=>{
reConnect();
});
return connection;
}
function reConnect() {
if (mongoose.connection.readyState == 0) {
console.log(mongoose.connection.readyState);
//you can just try to connect here now.
// connect();
}
else {
console.log("I am already Connected");
}
}
connect();
module.exports = mongoose;
so i've used mongoose
here, you can follow the way i have handled the error.in Mongoclient Docs i saw, it supports callback as well. so you can probably handle the error in the same way. the properties like .connection
and all those may not match though.