Node Express MongoDB Native Driver — Where to open the DB connection? Node Express MongoDB Native Driver — Where to open the DB connection? mongodb mongodb

Node Express MongoDB Native Driver — Where to open the DB connection?


JavaScript uses lexical scoping - meaning, if you did this it would work:

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`});

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.

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:

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; }};

Then in your index.js file:

var products = require('mongoconnect').getProducts();

Another option (if you want to keep just app and index) is to use a pair of closures:

index.js:

module.exports = function(products) {  return function index(req, res, next) {    console.log(products); // will have closed-over scope now  };};

app.js, inside of mongoClient.open(), where products is defined:

var index = require('./index')(products);