Meteor:如何通过会话变量过滤数据

时间:2016-01-19 16:25:17

标签: javascript mongodb session meteor

我有三个按钮来显示不同类型的信息

  1. 查看全部(即新闻与活动)
  2. 只有新闻
  3. 只有活动
  4. 状态:仅过滤新闻或事件有效。但如何看待两者?

    我的问题是将mongodb查询与会话变量结合使用。注释掉的线显示失败的方法。在我失败的方法中,我试图将更多内容放入会话值(即添加单词类型)。但是,这打破了所有疑问。

    我的js文件:

    Template.newsEvents.helpers({
      newsEventsData: function () {
        // return NewsEvents.find({Session.get('newsEventsView')}, {sort: {createdAt: -1}, limit: 3});
        return NewsEvents.find({type: Session.get('newsEventsView')}, {sort: {createdAt: -1}, limit: 3});
      }
    });
    
    Template.newsEvents.events({
        'click #js-seeAll': function (evt, tpl) {
            //Session.set('newsEventsView', '$or: [ { type: "news" }, { type: "event" } ]');
    
        },
        'click #js-seeNews': function (evt, tpl) {
            //Session.set('newsEventsView', 'type: "news"');
            Session.set('newsEventsView', 'news');
        },
        'click #js-seeEvents': function (evt, tpl) {
            //Session.set('newsEventsView', 'type: "event"');
            Session.set('newsEventsView', 'event');
        }
    });
    

    我的JSON文件:

    {
        "_id" : "7sLK32LdoLv4NmtMJ",
        "title" : "3rd News",
        "description" : "Some News",
        "type" : "news",
        "createdAt" : ISODate("2016-01-18T11:23:36.412Z")
    }
    

    任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

使用$ in子句并使用数组作为Session变量' newsEventsView'。我个人使用它来根据消息类型过滤消息。消息的类型将添加到存储为Session变量的数组中,然后传递给$ in子句。如果用户不想看到某种类型,他们会单击一个更新Session变量的按钮。你的代码看起来像这样:

Template.newsEvents.events({
    'click #js-seeAll': function (evt, tpl) {
        Session.set('newsEventsView', [ "news", "event" ]);
    }
});

Template.newsEvents.helpers({
    newsEventsData: function () {
        return NewsEvents.find({
            type: {
                $in: Session.get('newsEventsView')
            }, 
            {
                sort: {
                    createdAt: -1
                }, 
                limit: 3
            }
        });
    }
});
相关问题