Preface: Updating for mongodb 3.2 compatibility ... there are several fields that were previously set on actions that are no longer being set.
Have tried searching stackoverflow (which is where I discovered them originally) but have not located any info.
[db].openCalled :: used to be boolean once open() has been called, no longer there or moved
[db]._state :: used to indicate the "state" (e.g. "connected"), no longer there or moved
[db].serverConfig.checkoutWriter() :: this would return an Error under certain failure conditions
Anyone have guidance on how to update the following code to achieve the same results?
exports.getMongoDBConnection = function(callback) {
if (pooledConnection && pooledConnection.openCalled)
{
if (!!callback && typeof(callback) === "function") { callback(null, pooledConnection); }
}
else { // circa 2.2 always entering this since openCalled is gone
logging.info("No available pooled connection, opening new mongo connection.");
MongoClient.connect(connectionString, mongoOptions, function (err, db) {
if (err) {
var error = "Error connecting to Mongo: " + err;
logging.error(error, err);
if (!!callback && typeof(callback) === "function") { callback(err); }
} else {
pooledConnection = db; // cache the connection
db.on('close', function() {
if (db === pooledConnection) pooledConnection = null;
if (this._callBackStore) {
for(var key in this._callBackStore._notReplied) {
this._callHandler(key, null, 'Connection Closed!'); // notify any pending requests
}
}
});
db.on('reconnect', function() {
logging.warn("mongoHelper.js", 'Mongo reconnect detected');
if (this._callBackStore) {
for(var key in this._callBackStore._notReplied) {
this._callHandler(key, null, 'Connection reconnected, waiting queries are no longer valid');
}
}
});
...
exports.closeMongoDBConnection = function(db,force,callback) {
if (db && db.openCalled) {
var connection = db.serverConfig.checkoutWriter();
if (!!connection && connection instanceof Error) {
logging.warn("Closing failed mongo connection", connection);
force = true;
}
if ((force || db !== pooledConnection)) {
logging.info("Closing mongo connection in state: " + db.
_state);
return db.close(true, callback);
}
}
else if (!!callback && typeof(callback) === "function") callback(null,db);
};