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

如何将Firestore用户收藏文档ID传入函数查询对应帖子?

解决类Instagram应用中获取用户收藏帖子的问题

现有代码的问题

  1. FindUserSavedPosts 无返回值,无法传递获取到的收藏ID列表
  2. 循环调用 FetchUserSavedPosts 逐个查询帖子,效率低下且未收集结果
  3. FetchUserSavedPosts 中存在拼写错误:wherefield 应为 whereField

优化后的解决方案

1. 修改获取收藏帖子ID的函数,返回ID数组

static func fetchUserSavedPostIDs(uid: String) async throws -> [String] {
    let snapshot = try await Firestore.firestore()
        .collection("users")
        .document(uid)
        .collection("user-saves")
        .getDocuments()
    return snapshot.documents.map { $0.documentID }
}

2. 修改帖子查询函数,支持批量查询多个ID

static func fetchPostsByIDs(postIDs: [String]) async throws -> [Post] {
    guard !postIDs.isEmpty else { return [] }
    
    let postSnapshot = try await Firestore.firestore()
        .collection("posts")
        .whereField("id", in: postIDs)
        .getDocuments()
    
    return try postSnapshot.documents.compactMap { try $0.data(as: Post.self) }
}

3. 整合调用,获取用户所有收藏帖子

static func fetchUserSavedPosts(uid: String) async throws -> [Post] {
    let savedPostIDs = try await fetchUserSavedPostIDs(uid: uid)
    return try await fetchPostsByIDs(postIDs: savedPostIDs)
}

代码说明

  • fetchUserSavedPostIDs 负责从 user-saves 集合提取所有收藏的帖子ID,返回字符串数组
  • fetchPostsByIDs 使用Firestore的 whereField(_:in:) 批量查询匹配帖子,避免多次请求提升效率
  • fetchUserSavedPosts 作为入口函数,先获取ID列表再批量查询,最终返回用户所有收藏帖子

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:27:07