简体   繁体   English

Express.js res.render呈现多个数据源

[英]Express.js res.render to render multiple datas sources

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. 我对Node.js和Express.js比较满意,并且想知道我是否可以就为何某些数据无法渲染提出一些建议。 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. 如果我在ArticleModel.find中具有res.render,它将返回要传递到模板的数据,但是由于我有多个数据源,因此我希望res.render尽可能独立。 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? 除了教授Hello World / Todo应用程序之外,还有其他在线学习资源可用于Node.js和Express.js并显示出对应用程序开发的真正了解吗?

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 如果在所有路由中都需要一些数据,则可以移动数据检索(并可能需要一些缓存策略)来表达中间件并将结果分配给req对象属性

     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. 更常见的是,您可以使用promise或async库来改善复杂逻辑的代码组织。 It allows you to have better maintainable code. 它使您可以拥有更好的可维护代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM