Javascript 从meteor中的集合检索数据
我试图显示以表单形式提交的所有信息的汇总Javascript 从meteor中的集合检索数据,javascript,meteor,Javascript,Meteor,我试图显示以表单形式提交的所有信息的汇总 Template.SingleDailylog.helpers({ 人物负责人:()=>{ const id=FlowRouter.getParam('id'); const profile=dailyllog.findOne({u id:id}); const name=profile.personInCharge; 返回名称; } }); 负责人 帮助程序正试图从尚不存在的对象(配置文件)访问嵌套值(personInCharge) 如果要防止发生
Template.SingleDailylog.helpers({
人物负责人:()=>{
const id=FlowRouter.getParam('id');
const profile=dailyllog.findOne({u id:id});
const name=profile.personInCharge;
返回名称;
}
});代码>
负责人
帮助程序正试图从尚不存在的对象(配置文件
)访问嵌套值(personInCharge
)
如果要防止发生此异常,这里有两个选项:
选项1-禁止访问辅助对象中未定义的对象
例如,您可以将每个变量包装在if语句中,如下所示:
Template.SingleDailylog.helpers({
personInCharge: ()=>{
const id, profile, name;
id = FlowRouter.getParam('id');
if (id) {
profile = Dailylog.findOne({_id:id});
}
if (profile && profile.personInCharge) { // I always check nested things this way
name = profile.personInCharge;
}
if (name) {
return name;
}
});
在这种情况下,如果id
和profile
和profile.personInCharge
未定义,则不会执行if块中的代码,因此在创建模板时不会尝试访问尚不存在的嵌套变量,这将防止帮助程序引发异常
选项2-防止调用帮助程序
您还可以使用一个被动变量来指示订阅是否已准备就绪,并防止模板调用帮助程序(如果未准备就绪)
//常量订阅=/。。。如果使用全局订阅,请使用此选项
Template.SingleDailylog.onCreated (function () {
const instance = this;
instance.state = new ReactiveDict();
instance.autorun(() => {
const subscription = //... use this for Template level subscription
if (subscription.ready()) {
instance.state.set('loadComplete', true);
}
});
})
然后为loadComplete
添加帮助程序:
Template.SingleDailylog.helpers({
personInCharge() {
const id = FlowRouter.getParam('id');
const profile = Dailylog.findOne({_id:id});
const name = profile.personInCharge;
return name;
},
loadComplete () {
return Template.instance().state.get('loadComplete');
}
});
仅当loadComplete
为true时,才使用它调用PersonCharge
帮助程序:
<div class="form-group col-md-6">
{{#if loadComplete}}
<input value="{{personInCharge}}" type="text" class="form-control" placeholder="Name">
<label for="first">Person In Charge</label>
{{else}}
<div>Loading....</div>
{{/if}}
</div>
{{#如果加载完成}
负责人
{{else}
加载。。。。
{{/if}
这很可能是因为在第一次渲染中,订阅尚未准备好,因此助手会抛出一个错误。然后,一旦sub准备就绪,数据就可用了,没有错误,您的输入值设置为任何名称。我添加了另一个选项,以便您可以选择更适合当前代码的选项。@Jankapunkt非常感谢您的回答。我尝试了选项1,错误消失了!!但我不知道如何利用它来约会。代码为:Template.SingleDailylog.helpers({date:function(){const id=FlowRouter.getParam('id');if(id){profile=Dailylog.findOne({u id:id});}if(profile&&profile.date){name=profile.date;}if(name){return moment(name).format('MM/DD/yyyyy');},我得到一个错误:弃用警告:提供的值不是公认的ISO格式。即时构造返回到js Date(),这在所有浏览器和应用程序中都不可靠versions@Kassie如果解决方案对您有所帮助,请投票并接受(注意,选项1由@Ticdoc提供)。关于您的其他问题,我建议您针对日期错误提出一个新问题(因为该错误与Meteor或模板助手无关)。