从流星中的一个集合中检索数据



我正在尝试显示表单中提交的所有信息的总和。

Template.SingleDailylog.helpers({
personInCharge: ()=>{
const id = FlowRouter.getParam('id');
const profile = Dailylog.findOne({_id:id});
const name = profile.personInCharge;
return name;
}
});
<div class="form-group col-md-6">
<input value="{{personInCharge}}" type="text" class="form-control" placeholder="Name">
<label for="first">Person In Charge</label>
</div>

这确实插入了信息,但我仍然收到一个错误:

metro.js?hash=0504f43f667698535416b00eb44eb6f53161cb63:1048模板帮助程序中出现异常:TypeError:无法读取未定义的属性"personInCharge"在Object.personInCharge(http://localhost:3000/app/app.js?hash=e537a3bd311bc41765fe473a7cd9cf9609139dc9:8544:26)在http://localhost:3000/packages/blaze.js?hash=adc5286b78e5c0f8e7f56a602f77eefb5def6bf1:3051:16在http://localhost:3000/packages/blaze.js?hash=adc5286b78e5c0f8e7f56a602f77eefb5def6bf1:1715:16在http://localhost:3000/packages/blaze.js?hash=adc5286b78e5c0f8e7f56a602f77eefb5def6bf1:3103:66在Function.Template_withTemplateInstanceFunc

我怎么会出现错误,但显示的数据是正确的?这使我无法保存对数据的编辑。

帮助程序正试图从尚未存在的对象(profile)访问嵌套值(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;
}
});

在这种情况下,如果idprofileprofile.personInCharge未定义,则if块中的代码将不会执行,因此在创建模板时,它不会尝试访问尚不存在的嵌套变量,这将防止助手抛出异常。

选项2-阻止调用助手

您还可以使用一个反应变量来指示订阅是否准备就绪,并阻止模板调用助手(如果没有)。

//const订阅=//。。。如果您使用全局预订,请使用此选项

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为真时使用它来调用personInCharge助手:

<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>

最新更新