Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I made a very simple module <a href="https://github.com/baryshev/hub" rel="nofollow">hub</a> for this case that replaces the use of a global space.</p> <p>In app.js you can create db connection once:</p> <pre class="lang-js prettyprint-override"><code>var hub = require('hub'); hub.db = new Db('foobar', new Server('10.0.2.15', 27017, {}), {native_parser: false}); </code></pre> <p>And use it from any other files:</p> <pre class="lang-js prettyprint-override"><code>var hub = require('hub'); // hub.db - here link to db connection </code></pre> <p>This method uses a feature of 'require'. Module is only loaded for the first time and all the other calls gets a reference to an already loaded instance.</p> <p><strong>UPDATE</strong></p> <p>That's what I mean:</p> <p>In main file like app.js we create Db connection, open it and store into hub:</p> <p>app.js:</p> <pre class="lang-js prettyprint-override"><code>var hub = require('hub'); hub.mongodb = require('mongodb'); hub.mongodbClient = new hub.mongodb.Db('foobar', new hub.mongodb.Server('10.0.2.15', 27017, {}), {native_parser: false}); hub.mongodbClient.open(function(error) { console.log('opened'); }); </code></pre> <p>Now in any other file (message for example) we have access to opened connection and can simple use it:</p> <p>message.js:</p> <pre class="lang-js prettyprint-override"><code>var hub = require('hub'); var collection = new hub.mongodb.Collection(hub.mongodbClient, 'message'); module.exports.count = function(cb) { collection.count({}, function(err, count) { cb(err, count); }); }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload