2

My server need to handle too many requests (ex:100 req/sec) at a time and it involves db(mongodb) operations. To accomplish that, I've chosen Express Server to handle those request. I set up server with the express. Here I want to create only one db-connection for entire server.

To achieve it: in app.js

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/testdb1');

app.use(function (req, res, next) {
    req.db1 = db;
    //console.log(req.db1);
    next();
});

in routes.js

router.get('/user', function (req, res) {
    if (req) {        
     find = {};
     var db1 = req.db1;
     var userCollection = db1.get(collections.user);
     var testCollection1 = db1.get(collections.testTable1);
     var testCollection2 = db1.get(collections.testTable2);

     userCollection.find(find, function (err, doc) {
         console.log('1');
     });
     testCollection1.find(find, function (err, doc) {
           console.log('2');
     });
     testCollection2.find(find, function (err, doc) {
           console.log('3');
     });
    }
});

And the Problem is:

Let current mongodb connections(cmc) = 1; server creates one connection as it lifts(cmc++). When I make a request to route(/user) another connection is created(cmc++) for the first time. When I make a request again, one more connection is created(cmc++). After that although I made a number of requests to that route the count remains the same(cmc=4). What exactly happening there ? I need to update more collections when request is made. As no.of operations on collections increases connection count increasing. why the connection count is increasing. I want to create only one connection.

chikku
  • 863
  • 1
  • 7
  • 19
  • 3
    Where exactly are you getting these connection counts from? It might seem that your method of counting is possibly flawed. You also don't seem to realise such things as your "three" calls shown above would acutally ask for "three" connections in all likelihood, since they would in fact be acting in parallel. If you are expecting them to "block" one after the other, then that is not how async programming works ( deliberately ). That I would deem to be your main problem here. Do some more research on async methods and callbacks to understand them, – Blakes Seven Mar 03 '16 at 12:07
  • 1
    I am getting connection count from "db.serverStatus.connections". By using callbacks the count is not increasing (Realized after doing it). Because of that the execution might take long time(5crore data count collection). That is why I am going with parallel connections. My main doubt is instead of not using single db connection why it is creating another connection. – chikku Mar 03 '16 at 12:32

0 Answers0