title: Node.js reuse MongoDB reference
body: <p>I am having trouble understanding node.js.</p>
  
  <p>Example, MongoDB access, here's what I've got (mydb.js):</p>
  
  <pre><code>var mongodb = require('mongodb'),
      server = new mongodb.Server('staff.mongohq.com', 10030, {
          auto_reconnect: true
      }),
      db = new mongodb.Db('mydb', server);
  
  function authenticateAndGo(db, handle) {
      db.authenticate('username', 'password', function(err) {
          if (err) {
              console.log(err);
              return;
          }
          console.log('Database user authenticated');
  
          var collection = new mongodb.Collection(db, 'test');
  
          handle(collection);
      });
  }
  
  function query(handle) {
      db.open(function(err, db) {
          if( err ) {
              console.log(err);
              return;
          }
          console.log('Database connected');
  
          authenticateAndGo(db, handle);
      });
  };
  exports.query = query;
  </code></pre>
  
  <p>So, if I want to use it later, I would</p>
  
  <pre><code>var mydb = require('./mydb');
  mydb.query(function(collection) {
      collection.find({}, {
          limit: 10
      }).toArray(function(err, docs) {
          console.log(docs);
      });
  });
  </code></pre>
  
  <p>But, If I do multiple calls, like so:</p>
  
  <pre><code>var mydb = require('./mydb');
  mydb.query(function(collection) {
      collection.find({}, {
          limit: 10
      }).toArray(function(err, docs) {
          console.log(docs);
      });
  });
  mydb.query(function(collection) {
      collection.find({}, {
          limit: 10
      }).toArray(function(err, docs) {
          console.log(docs);
      });
  });
  </code></pre>
  
  <p>I get an exception:</p>
  
  <pre><code>Error: db object already connecting, open cannot be called multiple times
  </code></pre>
  
  <p>I think that there is really something fundamental that I do not understand about all this and it is probable that this question is stupid ...</p>
  
  <p>Anyway, all help is welcome.</p>
  
  <p>Thanks in advance.</p>