【问题标题】:How can I load data from mongo before the page load with KeystoneJS?如何在使用 KeystoneJS 加载页面之前从 mongo 加载数据?
【发布时间】:2018-01-16 11:59:11
【问题描述】:

我将 KeystoneJS 与 Handlebars 一起用于视图。我一直在尝试从 MongoDB 获取公司列表以加载到导航栏中,但没有成功。我知道去哪里更新 navLinks,我可以在一个页面上从 mongodb 加载公司。我想在导航的所有页面上加载公司列表,并且公司列表不是静态的。在导航呈现之前,我应该将代码放在哪里来加载数据?

【问题讨论】:

    标签: mongodb express handlebars.js middleware keystonejs


    【解决方案1】:

    您可以在 routes/middleware.js 中的 'initLocals' 中间件中添加自己的局部变量,该中间件将在路由控制器执行之前运行:

    routes/middleware.js

    exports.initLocals = function(req, res, next) {
    
        var locals = res.locals;
    
        locals.user = req.user;
    
        // Add your own local variables here
    
        next();
    
    };
    

    查看 Keystone.js 文档中的 Common Route Middleware 部分: http://keystonejs.com/docs/getting-started/

    【讨论】:

      【解决方案2】:

      终于搞定了

      exports.initLocals = function (req, res, next) {
              res.locals.navLinks = [
                  { label: 'Accueil',         key: 'home',        href: '/' },
                  { label: 'Projets',         key: 'projects',    href: '/projects' },
                  { label: 'Contacts',        key: 'users',       href: '/contacts' },
                  { label: 'Livrables',       key: 'deliverables',href: '/deliverables' },
                  { label: 'Fichier sources', key: 'sources',     href: '/sources' }
              ];
      
              //Get available companies for the user
              var view = new keystone.View(req,res);
              view.query('companies', keystone.list('Company').model.find().populate('project').sort('title')).then(function (err, results, next) {
                  if (err) return next(err);
                  next();
              });
              view.render(function(){
                  next();
              });
          };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 1970-01-01
        • 2013-12-29
        • 2022-01-17
        • 2010-12-23
        相关资源
        最近更新 更多