【问题标题】:How to use meteor limit properly如何正确使用流星限制
【发布时间】:2013-10-03 13:50:27
【问题描述】:

我想在流星中运行查询并将返回的字段数限制为 5。这是我的代码:

var courses =  Courses.find(
    {   day_of_week : {$in: day_selector}, 
        price : {$gt : price_min, $lt : price_max}, 
        starts : {$gt : schedule_min},
        ends : {$lt : schedule_max}}, 
            {limit : 10});
console.log(courses);
return courses;

但是,当我这样做时,我会在控制台日志中获得所有适合选择器的课程,而不仅仅是其中的 10 个。在模板中一切正常,只显示了 10 门课程。

我看了这个问题: Limit number of results in Meteor on the server side?

但这并没有帮助,因为我没有为我的课程使用特定的 _id 字段,我使用的是特定的 _id 字段,但用于其他集合。

【问题讨论】:

    标签: meteor limit


    【解决方案1】:

    目前,服务器正在发送您的整个课程集合,而您只是在客户端将它们过滤为 10。您实际上可以创建一个响应式订阅/发布来动态设置限制,或者您可以只限制在服务器上发送的记录数量

    Meteor.publish('courses', function(limit) {
      //default limit if none set
      var dl = limit || 10;
      return Posts.find({}, {limit: dl});
    });
    
    Meteor.subscribe('courses', Session.get('limit'));
    

    然后使用调用的事件动态设置限制:

    Session.set('limit', 5);
    

    【讨论】:

    • 很好的答案,但使用课程的模板在会话更改时不会呈现。知道为什么会这样吗?
    • 在发布上述评论之前,我已经在网上搜索了几个小时以寻找解决方案。一分钟后,我找到了解决方案:Deps.autorun(function() { Meteor.subscribe("courses", Session.get("limit")); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多