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

从Realtime Database转Firestore:如何用Document赋值给currentCustomer?

问题解决:Firestore替代Realtime Database的snapshot.child()方法

你的代码存在两个核心问题:Firestore引用创建错误,以及字段获取方式未切换到Firestore的API。以下是修正后的完整代码及说明:

修正后的MyUtil.kt代码

var currentCustomer: Customer? = null

fun fetchCurrentCustomer() {
    val uid = FirebaseAuth.getInstance().uid ?: return // 空值判断,避免后续空指针
    // 修正Firestore引用:集合名是REF_CUSTOMERS,文档ID是当前用户uid
    val ref = FirebaseFirestore.getInstance().collection(REF_CUSTOMERS).document(uid)

    ref.get().addOnSuccessListener { documentSnapshot ->
        if (documentSnapshot.exists()) { // 判断文档是否存在
            currentCustomer = Customer(
                id = documentSnapshot.id, // 获取文档ID对应原构造函数第一个参数
                fullname = documentSnapshot.getString("fullname")!!,
                username = documentSnapshot.getString("username")!!,
                email = documentSnapshot.getString("email")!!,
                "", // 此处对应原构造函数的空字符串参数,保持不变
                profileImageUrl = documentSnapshot.getString("profileImageUrl")!!
            )
        }
    }
}

关键修正点说明

  • Firestore引用创建:原代码中collection("/$REF_CUSTOMERS/$uid")是错误的,Firestore的collection()方法接收集合名称,document()方法指定集合下的具体文档ID。正确写法是先获取REF_CUSTOMERS集合,再通过document(uid)定位到当前用户的文档。
  • 字段获取方式:Firestore的DocumentSnapshot没有child()方法,替代方式是:
    • 使用getString("字段名")直接获取字符串类型字段
    • 如果需要指定类型,也可以用get("字段名", String::class.java)
  • 文档存在判断:用documentSnapshot.exists()替代原有的document != null,更准确判断目标文档是否存在。
  • 空值安全:开头增加uid ?: return,避免当用户未登录时uid为空导致后续操作报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:27:34