【问题标题】:Meteor Session.set() from mongodb property in helper function not working after deployMeteor Session.set() from mongodb property in helper function在部署后不起作用
【发布时间】:2014-01-22 12:28:33
【问题描述】:

我正在尝试从 mongodb 中的属性设置会话。我有这个在本地工作,但部署后我在控制台中收到此错误,并出现白屏死机。

Deps 重新计算异常:TypeError:无法读取属性 'siteTheme' 未定义

// helper
Handlebars.registerHelper("site", function(){
      host =  headers.get('host');
      theSite = Site.findOne({'domain': host});
      theme = theSite.siteTheme;  
      // Problem - Works locally, not deployed with mup.
      // Exception from Deps recompute: TypeError: Cannot read property 'siteTheme' of undefined 
      Session.set("theme", theme); 

      return theSite;
});



// Add theme class to html

siteTheme0 = function(){
  $('html').addClass('theme0');
};
siteTheme1 = function(){
  $('html').addClass('theme1');
};
siteTheme2 = function(){
  $('html').addClass('theme2');
};
siteTheme3 = function(){
  $('html').addClass('theme3');
};


// Change theme on change to db

Deps.autorun(function (c) {

  if (Session.equals("theme", "1")){
    siteTheme1();
  }
  else if (Session.equals("theme", "2")){
    siteTheme2();
  }
  else if (Session.equals("theme", "3")){
    siteTheme3();
  }
  else {
    Session.set("theme", "0");
    siteTheme0();
  }
});

【问题讨论】:

  • 打开 mongo 控制台并确保那里确实有数据。如果'domain':host 处没有数据,则不会返回任何内容,从而导致您的错误。为此,请在您的项目目录中打开一个终端并输入 meteor mongo 以访问您的 mongo shell。
  • 不相关但值得指出的是,您的车把辅助函数中的hosttheSitetheme 变量最终将成为全局变量。恐怕不好。你应该在它们前面加上var

标签: javascript mongodb meteor


【解决方案1】:

这是使用流星时最常遇到的问题之一。当你的助手被调用时你的集合数据还没有准备好(或者它不存在),所以Site.findOne返回undefined并且你不能访问undefinedsiteTheme。请参阅我对this question 的回答。基本上你只需要添加某种保护或返回语句并假设数据可能还没有准备好。例如:

Handlebars.registerHelper("site", function(){
  var host = headers.get('host');
  var theSite = Site.findOne({'domain': host});
  if (theSite) {
    var theme = theSite.siteTheme;
    Session.set("theme", theme);
    return theSite;
  }
});

如果您的其余代码编写正确,则您的模板应在数据准备好后立即重新呈现。

【讨论】:

  • 这正是我所缺少的,等待集合准备就绪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多