You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firestore中筛选并仅展示24小时内创建的Story帖子

实现24小时内Story帖子的筛选

你可以通过在Firestore查询中添加时间范围筛选条件来实现只获取24小时内发布的帖子,具体实现如下:

核心思路

先计算当前时间往前推24小时的时间节点,再通过Firestore的查询条件,只返回timestamp大于等于该节点的帖子,全程在服务器端完成筛选,比客户端过滤更高效。

修改后的完整代码

func fetchStories(completion: @escaping([Story]) -> Void) {
    // 计算24小时前的时间,转成Firestore兼容的Timestamp类型
    let twentyFourHoursAgo = Date().addingTimeInterval(-24 * 60 * 60)
    let timestampThreshold = Timestamp(date: twentyFourHoursAgo)
    
    Firestore.firestore().collection("stories")
        .whereField("timestamp", isGreaterThanOrEqualTo: timestampThreshold)
        .order(by: "timestamp", descending: true)
        .getDocuments { snapshot, _ in
            guard let documents = snapshot?.documents else { return }
            let stories = documents.compactMap({ try? $0.data(as: Story.self) })
            completion(stories)
        }
}

注意点

  • 如果Firestore控制台提示需要创建复合索引,直接按照提示的链接完成创建即可(因为同时使用了whereField和order(by)查询条件)。
  • 你的Story模型中timestamp字段已经是Firestore的Timestamp类型,和数据库字段类型完全匹配,无需额外转换。

内容的提问来源于stack exchange,提问作者robowarrior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:40:19