【问题标题】:How to publish a collection in Meteor that just sends the last 24 hours of data to the client?如何在 Meteor 中发布仅向客户端发送过去 24 小时数据的集合?
【发布时间】:2017-07-01 21:30:49
【问题描述】:
Meteor.publish('mountCarmelData', function dataPublication(){
    return MountCarmel.find({}, 
    {
        sort: {created_at: -1}
    });
});

有什么方法可以限制此发布仅发布过去 24 小时的数据?我在每条记录上都有一个名为“created_at”的时间戳。

【问题讨论】:

标签: javascript mongodb meteor


【解决方案1】:

您可以创建一个查询来做您想做的事,但问题在于订阅将数据拉到客户端而不删除旧数据的方式。您可以通过过滤客户端上的数据来解决此问题,使其仅显示 24 小时的数据,但如果让应用程序继续运行,则集合会变大,并可能在浏览器中占用过多内存。

我建议您单独收集 24 小时的数据。这使得在客户端的处理变得更加简单,因为您只需订阅数据。

看看这个问题和类似情况的答案:Publish only things who were read 10seconds ago from now

@jerome 成功使用了这种技术

【讨论】:

    【解决方案2】:

    您可以使用 moment.js 获取比当前日期正好少 24 小时的时间戳:

    let yesterday = moment().subtract(24, 'hours').toDate();

    然后在您的出版物中:

    Meteor.publish('mountCarmelData', function dataPublication(){
        return MountCarmel.find(
        {
            createdAt: { $gte : yesterday }
        }, 
        {});
    });
    

    我删除了“排序”,因为在服务器上排序不会导致您的文档在 MiniMongo 中排序。您需要在 Blaze 助手或 React Container 中添加“排序”才能使其工作。

    【讨论】:

    • yesterday 在您的代码中是一个时刻对象,而不是日期或时间戳。您可能应该在检查之前对其进行转换。
    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2014-10-24
    • 2017-05-16
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多