简体   繁体   中英

meteorjs and mongodb: how to group many collections into one

My application is a list of products.

I have too many, and want to group them, so I can refactor my publish/subscribe code (and my templates as well).

Assume 4 distinct collections in my mongodb: balloons, balls, tents, tea.

I need to group them into newly created foo and bar . Then I can write two publish/subscribe statements instead of 4, and access my data by doing something like:

on Client:

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

in html template

{{#each foo.balloons }}

    <p>{{ size }}</p>  
    <p>{{ price }}</p>

{{/each}}

or in another html template

{{#each bar.tents }}

    <p>{{ size }}</p>  
    <p>{{ price }}</p>

{{/each}}

Personally I would not group them into multiple collections. I would add a variable, such as "group" with the value "balloons", "balls", "tents" or "tea".

When you then subscribe, you can opt to subscribe to one or more groups at the same time. Then in your helpers, simply do something like:

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"
        });
    }
});

Update as per request:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM