Meteor:在模板接受Mongo查询结果之前修改它的最佳实践

Meteor : best practice for modifying Mongo query result before template takes it?

本文关键字:修改 最佳 结果 查询 Mongo Meteor      更新时间:2023-09-26

学习流星,我仍然陷入概念泥潭。

我有一个集合,其中每个项目都有一个名为"props"的数组,其中包含零个或多个属性名称:loudmouth、fixer、networker、outcaster等。

我还有一个属性对象的集合,每个对象都与一个字形图标相关联。

现在,我的模板将数据项显示为<li><li>包含属性标识符的行。我想用相应的图标HTML 替换属性标识符

{name: "loudmouth", icon: "bullhorn", other: "rtgb"}
{name: "fixer", icon: "wrench", other: "iun"}
{name: "networker", icon: "link", other: "retf"}
{name: "outcast", icon: "ban-circle", other: "vcfdds"}

所以这个。。。

<li>AAA loudmouth fixer outcast</li>
<li>BBB fixer networker</li>

应该变成这样。。。

<li>AAA <span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span> <span class="glyphicon glyphicon-wrench" aria-hidden="true"></span> <span class="glyphicon glyphicon-ban-circle" aria-hidden="true"></span></li>
<li>BBB <span class="glyphicon glyphicon-wrench" aria-hidden="true"></span> <span class="glyphicon glyphicon-link" aria-hidden="true"></span></li>

这不是SQL联接;我正在为每个返回的结果项添加属性。最好的方法是什么?

我试了好几种方法,但都弄得一团糟。

1) 第一个是客户端中一个粗糙的内部/外部循环作业。对于外部中的每个数据项,我会附加<span>从内部循环中的字符串连接的标记。这似乎给了我某种种族条件,带有虚假的"未定义"。(我还不清楚它的心理规律)。我应该将属性集合预取到名称/值映射对象中吗?此外,奇怪的是,我的HTML显示了<span>标记而不是图标?!?!嗯?

2) 然后,我尝试在服务器端使用Meteor.method和Meteor.call进行操作。我无法同步返回数据,也不知道如何(从回调)异步填充模板。是否在Template.mine.created()过程中填充数组,然后从Template.mine.helper返回数组?Meteor.method/Meter.call组合应该用于更改后端数据,而不是用于检索后端数据,我说得对吗?

有人知道关于这类事情的好教程吗?你会怎么做?

我希望这不会因为"基于意见"而被拒绝,我相信所有有效的替代方案都会帮助其他有相关问题需要解决的人。

您可以使用参数化模板:

<template name="glyph">
 <span class="glyphicon glyphicon-{{icon this}}" aria-hidden="true"></span>
</template>

添加一个助手函数,如:

Template.glyph.helpers({
    icon: function(name) {
            return <Iconcollection>.findOne({name:name}).icon
    }   
}); 

然后你可以在你的模板中做这样的事情:

{{> glyph 'fixer'}}

或者,如果参数来自迭代器对象

{{> glyph name}}

(假设您的对象具有.name属性)

无论如何,我建议你重读《流星》中的助手和反应性,并进行实验。由于客户端中已经有了集合,因此通常只需一个helper函数就可以解决这类问题。Meteor(重新)在集合更新时进行计算,因此您永远不必担心它。

检查我的理解:1个用户有1个属性。1属性具有1个name、1个icon、1个other

如果是这种情况,请在门口检查您的3NF;只需将它们嵌入到用户文档中即可。所以你的模式可能看起来像这样:

{userId: 'asldkfjz', 
 userName: 'Jonny', 
 properties: {
   name: "loudmouth", 
   icon: "bullhorn", 
   other: "rtgb"
 }
}

对于MongoDB,您总是需要权衡空间成本和访问成本。存储1个外键+一个额外的订阅可能比3个字符串更贵,对吧?

接下来,我将如何设置您的模板:

{{#each user}}
    {{>formatRow icon=properties.icon name=properties.name other=properties.other}}
{{/each}}
<template name="formatRow">
  <div class="blah">
    <li>{{name}} 
        <span class="glyphicon {{icon}}" aria-hidden="true"></span> 
    </li>
  </div>
</template>

我创建了一个包含3个变量的模板:iconnameother。然后,在我的主模板中,我传入这些变量。我将这两个步骤分开,因为以后可能会有比lispan多得多的垃圾,或者你想在另一个模板中这样做,这使它们保持模块化。

剩下要做的唯一一件事就是设置一个可以访问集合的模板助手:

Template.foo.helpers({
  user: function () {
    return users.find();
  }
});

更多信息,请访问:

http://docs.meteor.com/#/full/template_helpershttps://github.com/meteor/meteor/blob/devel/packages/spacebars/README.md