【问题标题】:Meteor: How to filter data via a session variableMeteor:如何通过会话变量过滤数据
【发布时间】:2016-04-25 05:27:17
【问题描述】:

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

  1. 查看全部(即新闻和事件)
  2. 只有新闻
  3. 仅限活动

状态:仅过滤新闻或事件有效。但是如何同时看到呢?

我的问题是结合会话变量编写 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")
}

任何帮助表示赞赏。

【问题讨论】:

    标签: javascript mongodb session meteor


    【解决方案1】:

    使用 $in 子句并为会话变量“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
                }
            });
        }
    });
    

    【讨论】:

    • 完美运行!你拯救了我的一天!
    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    相关资源
    最近更新 更多