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

如何在Firestore中获取users集合下的文档key(用户UID)

解决方案

Firestore 中 QueryDocumentSnapshot 提供的 documentID 属性,就等价于你之前在实时数据库中用到的 snapshot.key,对你的用户集合场景来说,这个值就是对应的用户 UID。

你只需要对原有代码做小幅调整即可:

  1. 首先修改你的 UserCollection 模型,增加 UID 存储属性,调整初始化方法接收 UID 参数:
struct UserCollection {
    let uid: String
    // 保留你原有的其他用户属性

    init(uid: String, dictionary: [String: Any]) {
        self.uid = uid
        // 保留你原有的从字典赋值其他属性的逻辑
    }
}
  1. 调整拉取用户集合时的映射逻辑,把每个文档的 documentID 传入初始化方法:
Firestore.firestore().collection("users").getDocuments { snapshot, _ in
    guard let documents = snapshot?.documents else { return }
    users = documents.map({ 
        UserCollection(uid: $0.documentID, dictionary: $0.data()) 
    })
}

如果你暂时不想调整原有模型的初始化方法,也可以在遍历时单独提取 UID 处理:

Firestore.firestore().collection("users").getDocuments { snapshot, _ in
    guard let documents = snapshot?.documents else { return }
    documents.forEach { doc in
        let uid = doc.documentID // 此处即可获取对应用户的 UID
        let user = UserCollection(dictionary: doc.data())
        // 执行你后续的业务逻辑
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:27:02