Arian
Arian

Reputation: 575

Close Nodejs mongodb idle connection

I want to close any mongodb(2.6.8) connection in my nodejs app in which if a conn stays idle for more than 5 seconds. I can think of a solution that by checking the connection stat using after every 5 second and if it’s idle then closing the conn.

Is there any better way to handle this case?

Upvotes: 1

Views: 767

Answers (1)

AlexD
AlexD

Reputation: 4290

If I understand correctly, you wish to count how long your MongoDB connection stays open and if it passes a certain threshold you will close it.

You can achieve it by wrapping the mongodb library with your own code, each time counting how long has passed since the last operation.

A sketch, didn't run it:

var mongodb = require('mongodb');
var client;
var lastRun;

// Need to run it once
function init() {
    client =  = mongodb.MongoClient.connect(...);
    lastRun = new Date();
    checkConnectionTimeout();
}

function checkConnectionTimeout() {
    var newDate = new Date();
    var seconds = Math.abs((newDate.getTime() - lastRun.getTime()) / 1000);
    if (seconds > TIMEOUT) {
        // close the connection...
        client = null;
    }
}

function execute(func, args) {
    lastRun = new Date();
    if (client) {
        client[func](args);
    }
}

Then you can use it by:

mongoWrapper.init(); // once
mongoWrapper.execute(collection.find, criteria);

Upvotes: 1

Related Questions