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

Firestore读取RechargeCoin集合并更新文档问题求助

问题1:读取所有RechargeCoin集合中的UID和PostID数据

你这段代码的核心问题是db.collection("Users").document().collection("RechargeCoin")里的document()未传参数,这会生成一个随机ID的空文档引用,根本无法遍历所有用户下的RechargeCoin集合。要实现需求,应该用collectionGroup查询,同时通过文档引用获取父文档的UID:

let db = Firestore.firestore()
// 用collectionGroup查询所有用户下的RechargeCoin集合
db.collectionGroup("RechargeCoin")
    .order(by: "date", descending: true)
    .addSnapshotListener { snapshot, error in
        guard let snapshot = snapshot else {
            print("查询失败: \(error?.localizedDescription ?? "未知错误")")
            return
        }
        for document in snapshot.documents {
            // 获取用户UID:RechargeCoin的父文档就是Users下的uid文档
            let uid = document.reference.parent.parent?.documentID ?? "未知UID"
            // 获取PostID:当前文档的ID就是postid
            let postId = document.documentID
            // 此处可处理拿到的uid和postId,比如存入数组或展示
            print("UID: \(uid), PostID: \(postId)")
        }
    }

注意:使用collectionGroup+order by查询前,需要在Firestore控制台创建对应的复合索引——代码运行后抛出的错误会附带索引创建链接,直接点击即可完成配置。

问题2:使用collectionGroup更新指定postID的文档失败

你直接在collectionGroup后调用document(postId)是错误的:collectionGroup包含所有用户下的RechargeCoin集合,同一个postId可能存在于多个用户的集合中,Firestore无法直接定位到具体文档。正确做法是先通过查询定位目标文档,再执行更新:

let targetPostId = self.postArray[indexPath.row].postId
fireStoreDB.collectionGroup("RechargeCoin")
    // 如果文档ID就是postId,用这个条件匹配文档ID
    .whereField(FieldPath.documentID(), isEqualTo: targetPostId)
    // 如果文档内有postId字段,也可以用.whereField("postId", isEqualTo: targetPostId)
    .getDocuments { snapshot, error in
        guard let snapshot = snapshot, !snapshot.isEmpty else {
            print("未找到目标文档: \(error?.localizedDescription ?? "未知错误")")
            return
        }
        // 若postId全局唯一,取第一个文档即可
        let targetDoc = snapshot.documents.first!
        targetDoc.reference.updateData(userInfo as [String: Any]) { error in
            if let error = error {
                print("更新失败: \(error.localizedDescription)")
            } else {
                print("更新成功")
            }
        }
    }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:05:32