Few months back I have upgraded to mongo db verstion to 3.6 and all node js driver to latest version. After that it is start generating following errors at random interval:
- MongoError: server is closed at Server.query
- MongoError: Cannot use a session that has ended at applySession
- MongoError: connection pool closed at ConnectionPool.close
- MongoError: pool destroyed at Pool.write
I am also not able to simulate these error as it worked most of the time and generate error once in a couple of weeks or once in a month.
Here is my mongo controller code:
function controller(environmentConfig) {
var mongo = require('mongodb').MongoClient,
db,
isAlreadyConnected = function () {
var isConnected = !!(db && db.topology.isConnected());
return isConnected;
},
connectFunction = function (callback) {
var cb = callback || function() {};
if(isAlreadyConnected()) {
return cb(db);
}
var options = {
server: {
socketOptions: {
connectTimeoutMS: 300000,
socketTimeoutMS: 300000,
keepAlive: 300000,
},
mongos: {
connectTimeoutMS: 300000,
socketTimeoutMS: 300000,
keepAlive: 300000,
}
}
};
mongo.connect(environmentConfig.databaseConnectionString, { useUnifiedTopology: true, useNewUrlParser: true }, options, function(connectionErr, newClient) {
// one final check
if(isAlreadyConnected()) {
// we do have a connection, so close this one
db.topology.close();
} else {
console.log('Mongo: now connected');
db = newClient.db(newClient.s.options.dbName);
}
return cb(db);
});
};
return {
connect: connectFunction,
getDb: function (callback) {
var cb = callback || function() {};
if(!isAlreadyConnected()) {
connectFunction(function(client) {
return cb(client);
});
return;
}
return cb(db);
}
}
}
module.exports = controller;