Question

I'm relatively green with Node.js and Express.js and was wondering if I could have some advice as to why some of my data isn't rendering. My code is as follows:

var mongoose    = require('mongoose'),
ArticleModel    = mongoose.model('Article');

exports.index = function (req, res){
    ArticleModel.find({}, function (err, articles){
        if(err) throw new Error(err);
    });
    res.render('home/index', {
        title: 'Business, Inc',
        articles: articles
    });
};

If I have the res.render inside ArticleModel.find, it will return data to be passed to my template, however I as I have multiple data sources, I would like my res.render to be more independent if possible. What's the best way that I could build data models to be used throughout my application.

Are there any online learning resources for Node.js and Express.js that go beyond teaching Hello World / Todo apps, and show some real depth into application development?

Was it helpful?

Solution

There are several ways:

  1. If you need some data in all routes, you could move data retrieval( and potentially some caching strategy) to express middleware and assign result to req object property

    module.exports = function getArticles() {
     return function getArticlesRetrieval(req, res, next) {
    
      ArticleModel.find({}, function (err, articles){
       if(err) return next(err);
    
       req.articles = articles;
       next();
      });  
    
     };
    
    };
    
  2. More commonly you could improve code organization for complex logic using promises or async libraries. It allows you to have better maintainable code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top