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

Passing references to express-resources in node.js?

Passing references to express-resources in node.js?

Problem

How can I pass for example the database reference

nano = require('nano')('http://127.0.0.1:5984')
db = nano.use('database')

to a resource 'User' (loaded with express-resource)?

I tried:

app.resource('user', require('./routes/user'), {db: db});

But that doesn't work.

Problem courtesy of: Patrick

Solution

You want to pass db to the user.js routing file. What you are doing is passing it to the app.resource function.

app.resource('user', require('./routes/user')(db));

You will have to wrap your user.js file in a function that can receive db as a parameter.

module.exports = function(db) {
  return {
      index: function(req, res) {}
    , new: function(req, res) {}
    , create: function(req, res) {}
    // etc
  };
};

If you don't like the way this is structured, you can also use a middleware.

app.use(function(req, res, next) {
  req.db = db;
  next();
});
Solution courtesy of: fent

Discussion

View additional discussion.



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

Share the post

Passing references to express-resources in node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×