krikara
krikara

Reputation: 2435

What is the difference between db.open and db.connect?

In my adventure of making a NodeJS HTTP server, I began with the code below. This server is supposed to be able to handle around 10,000 requests all occurring within the same second or two.

I was wondering what exactly is the difference between db.open and db.connect. The docs says "initialize DB connection" and "connect to DB" respectively, but this seems to be the same thing to me. Further more, they both use db.close() to close the connection. Is there one I should be using?

var server = http.createServer(function (req, res) {

     req.on('data', function(chunk) {
          //Do some stuff here
     });

     req.on('end', function() {
          //Do some stuff here
          var db = new Db('test', new Server("111.111.11.111", 27017,{auto_reconnect: false}), {safe: true});  

          db.open(function(err, db) {
               //Insert data into DB
               db.close();
          });
     });
}); //End Http server

Upvotes: 2

Views: 833

Answers (1)

necromos
necromos

Reputation: 442

First of all try to take out your database connection out from requests and keep it 1 per app. Mashing database with 10k connections when all clients wants to end their request is not a good idea. As far as I remember database have limited connection pool so this is the reason of yours bottleneck and errors. Unfortunately I cannot give right now good example for this one.

And as to "db.connect" and "db.open" difference is mostly in code usage. To be more precise here is connect and also open and as you can see connect is using connection string where open uses new DB which needs new Server declared to work.

Oh and one more thing, try to use higher level library for mongoDB connection such as mongoose (I cannot paste link in "nice way" so here it is: mongoosejs.com)

Upvotes: 3

Related Questions