Node.js mongodb errors when connections reach 130 opened connections

This is the example of request I am using:

app.get('/', function (req, res) {
     var user_hash = req.cookies.SESSION;

    db.connect(mongoURI, function (err, db) {
        var collection = db.collection('sessions');

        collection.findOne({hash: user_hash}, function (err, item) {
            res.render('index', {title: 'Домашняя страница', session: item !== null});
            db.close();
        });
    });
});

And I am havin a lot requests handeled like that.

The problem appear when I Apache Benchmark it the following command:

ab -n 100 -c100 http://127.0.0.1:8080

I recive the followin error:

cannon read property collection of null

My guess is, that after apache benchmark, opened connections on mongodb is 130 - 150. Now I am trying to get it more stable befor lunching my server in to the "battle". I heard about connectivity pools but can't figure it out.

Now the questions: Dose my server crash becaus of "to many opened connections on mongodb" or some thig else? What should I do to fix it?

It's not good practice to continually open and close connections to the back-end database as it will take some time for the resources to be returned to the OS. Which probably explains why you are seeing the error.

You could increase the ulimit on your mongod or mongos as described here, but given the type of testing you are trying to do I still think you'll run out of resources.

It probably makes more sense for you to use something like mongoose or the approach described here.

But if you really want to follow your current approach , you should wrap your express application:

Db.connect(mongoURI,function(err, db){
  if(err) {
    console.log("Error " , err);
    return;
  }
  var collection = db.collection('sessions');

  app.get('/', function (req, res) {
    var user_hash = req.cookies.SESSION;
    collection.findOne({hash: user_hash}, function (err, item) {
        res.render('index', {title: 'Домашняя страница', session: item !== null});
    });
  });

});