2016-02-05 135 views
2

我试图获取一个集合中有一个条目外取:流星客户端未定义帮手

客户端/视图/ home.js

criticalCrewNumber = ConfigValues.find({ 
    name: 'criticalCrewNumber' 
}).fetch()[0].value; 

但我发现了错误:

Uncaught TypeError: Cannot read property 'value' of undefined

如果我运行在浏览器控制台的代码,所期望的值返回一个字符串。

我尝试了各种各样的东西,例如使用findOne;将代码放在应用程序的其他地方;使用铁路路由器waitOn订阅来,等等。到目前为止,每次尝试失败,因为我最终undefined

这里的收集是如何定义,发布和订阅到:

的lib /配置/ admin_config.js

ConfigValues = new Mongo.Collection("configValues"); 

ConfigValues.attachSchema(new SimpleSchema({ 
    name: { 
    type: String, 
    label: "Name", 
    max: 200 
    }, 
    value: { 
    type: String, 
    label: "Value", 
    max: 200 
    } 
})); 

两/收藏/ eventsCollection.js

if (Meteor.isClient) { 
    Meteor.subscribe('events'); 
    Meteor.subscribe('config'); 
}; 

server/lib/collections.js

``` Meteor.publish('events',function(){ return Events.find(); }); ('config',function(){ return ConfigValues.find(); }); ```

有谁知道发生了什么事?谢谢。

+0

这是流星,非常常见的问题。你能说更多关于被调用的地方吗?例如它是在onCreated中,还是只在文件范围? –

+1

在调用'find'时,Minimongo中没有数据 - 数据库的本地副本 - 这就是为什么'.find(...)。fetch()'返回空数组的原因。当您在控制台中运行此行时,订阅已准备好并且数据已经可用。 –

+1

发布函数是什么样的? – Ivan

回答

1

考虑使用ReactiveVar(和Meteor.subscribe回调):

criticalCrewNumber = new ReactiveVar(); 

Meteor.subscribe('config', { 
    onReady: function() { 
     var config = ConfigValues.findOne({name: 'criticalCrewNumber'}); 
     if (config) { 
      criticalCrewNumber.set(config.value); 
     } else { 
      console.error('No config value.'); 
     } 
    }, 

    onStop: function (error) { 
     if (error) { 
      console.error(error); 
     } 
    } 
});