简体   繁体   English

尝试使用流星和蒙哥过滤基于“类别”的“行情”

[英]Trying to filter “Quotes” based on '“Category” using meteor & mongo

So I'm having a bit of trouble. 所以我有点麻烦。 I have a list of quotes, and each quote has category. 我有一个报价列表,每个报价都有类别。

I wasn't sure the best solution of how to architect this, so I decided to make 2 collections. 我不确定如何设计最佳的解决方案,所以我决定制作2个系列。 One for "Quotes" and one for "Categories". 一种用于“行情”,另一种用于“类别”。

Each "Quote" has a "Category" which is the _ID of the categories I inserted into the database. 每个“报价”都有一个“类别”,即我插入数据库中类别的_ID。

I'm trying to "Filter" the list of quotes based on the "Category" I click on in my webapp. 我试图根据我在Web应用程序中单击的“类别”来“过滤”报价列表。

I'm having trouble figuring out how to to this. 我很难弄清楚该如何做。

So far I've created a session which stores my "Clicked Category Id" but from there I don't know how to filter my "Quotes" database to show "ONLY QUOTES WITH CATEGORY ID = SESSION CAT_ID" 到目前为止,我已经创建了一个会话,用于存储“点击的类别ID”,但是从那里我不知道如何过滤“报价”数据库以显示“只有类别ID = SESSION CAT_ID的报价”

Any help is much appreciated. 任何帮助深表感谢。

You should really indicate what your current code looks like so we have a reference to start from. 您应该真正指出当前代码的样子,因此我们有一个参考。 However this is a fairly simple task so I've gone ahead and provided a mock example: 但是,这是一个相当简单的任务,因此我继续进行操作并提供了一个模拟示例:

Template: 模板:

{{#each quoteCategories}}
    <button class="quote-category" value="{{_id}}">{{title}}</button>
{{/each}}

<ul>
{{#each quotes}}
    <li>"{{content}}" &mdash; {{author}}</li>
{{/each}}
</ul>

Template events : 模板事件

Template.quotesList.events({
    'click button.quote-category': function(event) {
        var categoryId = $(event.target).val();
        Session.set('quote-category-id', categoryId);
    }
});

Template helpers : 模板助手

Template.quotesList.helpers({
    'quoteCategories': function() {
        return QuoteCategories.find({});
    },
    'quotes': function() {
        var categoryId = Session.get('quote-category-id');
        if(categoryId) {            
            return Quotes.find({category: categoryId});
        } else {
            return Quotes.find({});
        }
    }
});

Your Collection architecture is fine. 您的Collection架构很好。 One of the best things about a noSQL database like MongoDB is that you can really choose to normalise or denormalise depending on your needs. 关于像MongoDB这样的noSQL数据库的最好的事情之一是,您可以根据需要真正选择标准化或非标准化。 So for your structure if it's easier to work with as two Collections then that's fine. 因此,对于您的结构,如果更容易使用两个Collections,那就很好。 Generally speaking the best way to determine DB structure is to optimise for heaviest use, so make it simpler to be read for read-heavy applications (the majority) or easy to write (insert, update) for write-heavy applications. 一般而言,确定数据库结构的最佳方法是针对最繁重的使用进行优化,因此对于繁重的应用程序(大多数)而言,使其更易于读取,而对于繁重的应用程序而言,其易于编写(插入,更新)。 The structure can vary depending on these needs. 结构可以根据这些需求而变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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