Meteorjs和mongodb:如何将多个集合组合成一个

meteorjs and mongodb: how to group many collections into one

本文关键字:组合 集合 一个 mongodb Meteorjs      更新时间:2023-09-26

我的应用程序是一个产品列表。

我有太多,我想把它们分组,所以我可以重构我的publish/subscribe代码(和我的模板)。

假设我的mongodb中有4个不同的集合:balloons, balls, tents, tea.

我需要将它们分组为新创建的foobar。然后,我可以编写两条发布/订阅语句,而不是4条,并通过以下方式访问数据:

on Client:

Foo = new Meteor.Collection('foo');
Bar = new Meteor.Collection('bar');

{{#each foo.balloons }}
    <p>{{ size }}</p>  
    <p>{{ price }}</p>
{{/each}}

或在另一个HTML模板

{{#each bar.tents }}
    <p>{{ size }}</p>  
    <p>{{ price }}</p>
{{/each}}

我个人不会将它们分组到多个集合中。我会添加一个变量,例如"group",其值为"balloons","balls","tent"或"tea"。

当您订阅时,您可以选择同时订阅一个或多个组。然后在您的帮助程序中,简单地执行如下操作:

Template.foo.helpers({
    balloons : function() {
        return Foo.find({
            "group" : "balloons"
        });
    },
    tents : function() {
        return Foo.find({
            "group" : "tents"
        });
    }
});
Template.bar.helpers({
    balls : function() {
        return Foo.find({
            "group" : "balls"
        });
    },
    tea : function() {
        return Foo.find({
            "group" : "tea"
        });
    }
});

根据请求更新:

<body>
    {{> foo}}
    {{> bar}}
</body>
<template name="foo">
    <div id="balloons" class="product-list">
        {{#each balloons}}
            {{> productItem}}
        {{/each}}
    </div>
    <div id="tents" class="product-list">
        {{#each tents}}
            {{> productItem}}
        {{/each}}
    </div>
</template>
<template name="bar">
    <div id="balls" class="product-list">
        {{#each balls}}
            {{> productItem}}
        {{/each}}
    </div>
    <div id="tea" class="product-list">
        {{#each tea}}
            {{> productItem}}
        {{/each}}
    </div>
</template>
<template name="productItem">
    <div class="product">
        <h1>{{title}}</h1>
        <p>{{description}}</p>
    </div>
</template>