byrdr
byrdr

Reputation: 5487

Express routes, More DRY method of passing data to routes

I have several mongodb models, which I am passing through to my routes. The approach I'm taking leaves a lot of repeated code.

var AboutData    = mongoose.model( 'AboutData' );
var BlogData     = mongoose.model( 'BlogData' );

app.get('/about', function(req, res, next) {
  BlogData.find(function(err, blogitems){
     if(err) { return next(err); } 
   AboutData.find(function(err, items){
     if(err) { return next(err); }
     res.render('index.ejs',{
       homelist: ['home', 'about', 'services', 'volunteer', 'contact', 'give', 'blog'],
       aboutlist: items,
       bloglist: blogitems,
       bootstrappedUser: req.user,
       page: 'about'
     });
  });
});
});

Is there a better approach, that I could take to have multiple models be available all of my routes?

Upvotes: 0

Views: 144

Answers (1)

mscdex
mscdex

Reputation: 106696

You could create a middleware that sets common view variables by setting properties on res.locals. Here is one example:

app.use(function(req, res, next) {
  res.locals.bootstrappedUser = req.user;
  res.locals.homelist = [
    'home', 'about', 'services', 'volunteer', 'contact', 'give', 'blog'
  ];

  BlogData.find(function(err, blogitems) {
    if (err)
      return next(err);
    res.locals.bloglist = blogitems;
    next();
  });
});

app.get('/about', function(req, res, next) {
  AboutData.find(function(err, items){
    if (err)
      return next(err);

    // here `index.js` will have access to `bootstrappedUser`, `homelist`, and
    // `bloglist`
    res.render('index.ejs',{
      aboutlist: items,
      page: 'about'
    });
  });
});

You can also set variables in the same fashion on the app.locals object. Typically you set static values that are not request-specific on app.locals during set up of your Express app and set dynamic request-specific values on res.locals.

Upvotes: 1

Related Questions