Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>JavaScript uses lexical scoping - meaning, if you did this it would work:</p> <pre><code>var mongoClient = new MongoClient(new Server('localhost', 27017)); mongoClient.open(function(err, mongoClient) { var db1 = mongoClient.db("dev-db") , products = db1.collection('products'); app.get('/', function closedOverIndexRoute(req, res, next) { console.log(products); // this will work }); app.get('/users', user.list); // however, user.list will not be able to see `products` }); </code></pre> <p>A function doesn't become a closure (doesn't retain the values of its enclosing function) unless it's lexically (written) inside of the closure.</p> <p>However, you probably don't want to write your whole app as one big closure. Instead, you can use exports and require to get access to your products collection. For example, in a file called mongoconnect.js:</p> <pre><code>var mongoClient = new MongoClient(new Server('localhost', 27017)); var products; mongoClient.open(function(err, mongoClient) { var db1 = mongoClient.db("dev-db"); products = db1.collection('products'); }); module.exports = { getProducts: function() { return products; } }; </code></pre> <p>Then in your index.js file:</p> <pre><code>var products = require('mongoconnect').getProducts(); </code></pre> <p><strong>Another option (if you want to keep just app and index) is to use a pair of closures:</strong></p> <p>index.js:</p> <pre><code>module.exports = function(products) { return function index(req, res, next) { console.log(products); // will have closed-over scope now }; }; </code></pre> <p>app.js, inside of <code>mongoClient.open()</code>, where <code>products</code> is defined:</p> <pre><code>var index = require('./index')(products); </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