Meteor 流星:如何激活模板';设置变量时的辅助对象

Meteor 流星:如何激活模板';设置变量时的辅助对象,meteor,Meteor,我有一个助手: Template.showScannedData.helpers({ 'lastConnectionNetId': function(){ return Connections.findOne().netId; } }); 与以下模板关联: <template name="showScannedData"> {{#if lastConnectionNetId}}} my last connection's i

我有一个助手:

Template.showScannedData.helpers({
    'lastConnectionNetId': function(){ 
        return Connections.findOne().netId; 
    }
});
与以下模板关联:

<template name="showScannedData">
    {{#if lastConnectionNetId}}}
       my last connection's id: {{lastConnectionNetId}}<br>
    {{/if}}
</template>

{{{#如果LastConnectionNode}}
我的上一个连接的id:{{lastConnectionTID}}
{{/if}
问题是,在我没有向连接收集添加任何内容之前(这是在Cordova内完成的,通过从NFC标记获取一些数据,然后将其存储在MongoDB中),我会得到以下异常:

模板帮助程序中出现异常:TypeError:无法读取未定义的属性“netId”

我理解,该异常是由数据可用之前激活的模板引起的

此外,为了向用户“隐藏”问题(即不显示不完整的UI),我在模板中添加了一个检查

如果最后连接

这样做对吗


只要集合为空,如何避免获取异常?

在您的情况下,findOne返回一个对象。如果没有文档满足查询,则该方法返回null。这意味着您的对象将是空的,netId将是未定义的。我想试试这个:

Template.showScannedData.helpers({
    'lastConnection': function(){ 
        return Connections.findOne(); 
    }
});

<template name="showScannedData">
    {{#if lastConnection}}}
       my last connection's id: {{lastConnection.netId}}<br>
    {{/if}}
</template>
Template.showScannedData.helpers({
“lastConnection”:函数(){
返回连接。findOne();
}
});
{{{#如果最后连接}}}
我的上一个连接的id:{{lastConnection.netId}}
{{/if}

这可以解决您的问题。

您应该查看我之前的评论,您需要等待数据加载

此外,如果仍然不确定集合中是否存在任何数据,则应创建以下帮助器:

 'lastConnectionNetId': function(){ 
   return Connections.findOne() && Connections.findOne().netId; 
 }
更多关于Meteor中防御编程的信息可供参考