Search code examples
javascriptnode.jsmongodbmongoskin

Why explicitly .open() a connection in MongoDB?


I have this connection set:

var db = mongo.db('mongodb://localhost/inline_dev', {native_parser:true});

I then open a connection, and fetch some document...

db.open(function(err, db)
db.collection('test').find().toArray(function(err, dbDocs) {
  if (!err) {
    console.log(dbDocs)
    }
  });

... but this seems to work as well, without the explicit .open():

db.collection('test').find().toArray(function(err, dbDocs) {
  if (!err) {
    console.log(dbDocs)
    }
  });

Q) Why can/should I explicitly open() the connection, given that it seems like the connection is opened as soon as I try to query a collection anyway?

Actually, it seems like the connection is opened as soon as I point my browser to the URL of the app (at least according to the mongod log).


Solution

  • Mongoskin as much like other implementations do some "funny stuff" to cover up an initial connection which should actually be done in a callback. So really you should be waiting for the "open" to complete, but the actual process is "hidden" by holding the other operations until the connection is made.

    A good way to illustrate it to inspect the Object from each in code:

    var mongo = require('mongoskin');
    var db = mongo.db("mongodb://localhost/test");
    
    console.log( "Before" );
    console.log( db );
    db.open(function(err,conn) {
      console.log( "After" );
      console.log( conn );
      console.log( "And DB:" );
      console.log( db );
    });
    

    But to your code in general it should not make a difference.