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

Kotlin+Firestore:如何为指定userId的Firestore文档添加字段?

问题原因

你调用update失败的核心原因是:db.collection("users").whereEqualTo("userId", userId)返回的是Query(查询对象),Firestore的Query类并没有直接提供update或set方法——这两个方法是属于单个文档的DocumentReference对象的。

解决方案

要更新符合条件的文档,你需要先执行查询获取匹配的文档,再对每个文档的引用调用update方法。因为userId应该是唯一标识用户的字段,通常只会匹配到一个文档,代码可以这么写:

binding.registerBtn.setOnClickListener {
    // 注意:建议和首次存入时保持一致,改用selectedItem.toString()避免获取View本身的字符串
    val communityValue = binding.communityInput.selectedItem.toString()
    val communityMap = hashMapOf("community" to communityValue)

    db.collection("users")
        .whereEqualTo("userId", userId)
        .get() // 执行查询,获取匹配的文档快照
        .addOnSuccessListener { querySnapshot ->
            // 遍历查询结果(userId唯一的话,只会有一个匹配文档)
            for (document in querySnapshot.documents) {
                document.reference.update(communityMap)
                    .addOnSuccessListener {
                        startActivity(Intent(this@CommunityRegisterActivity, DiaryActivity::class.java))
                    }
                    .addOnFailureListener { e ->
                        // 处理更新失败的情况,比如打印日志或提示用户
                        Log.e("Firestore", "更新文档失败", e)
                    }
            }
            // 处理无匹配文档的情况
            if (querySnapshot.isEmpty) {
                Log.w("Firestore", "未找到userId为$userId的用户文档")
            }
        }
        .addOnFailureListener { e ->
            // 处理查询失败的情况
            Log.e("Firestore", "查询用户文档失败", e)
        }
}
额外注意事项
  • 确保userId的类型和首次存入时一致:你第一次存的是auth.currentUser(FirebaseUser对象),但通常推荐存储auth.currentUser?.uid(用户唯一ID字符串),如果之前存的是对象,查询时必须用相同的对象才能匹配到。
  • 避免直接调用binding.communityInput.toString(),这会返回View的类名+哈希值,而非选中的选项内容,和首次存入逻辑保持一致用selectedItem.toString()更合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:35:43