Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to transfer variable to routes.index

How to transfer variable to routes.index


In file app.js i have:

  , mongoose = require('mongoose')
  , db = mongoose.connect('mongodb://localhost/expressdb');

  app.get('/', routes.index);

and i have file routes/index.js, If I want to transfer db variable to routes.index What should I do?

Problem courtesy of: Huy Tran


I've setup an example on how you can achieve that, by passing the db as a parameter to the route module, and that module returns a function (in which db is visible):


module.exports = function (db) {
  return function(req, res, next) {
    // you can access db here


routes = {};
routes.index = require('./routes')(db);
Solution courtesy of: alessioalex


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to transfer variable to routes.index


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription