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

Kotlin中如何从Firestore的DocumentSnapshot提取指定key的animeId

从Firestore DocumentSnapshot中提取animeId字段

我从Firestore的Users集合获取到了DocumentSnapshot列表,现在需要过滤提取每个文档里的animeId字段。当前代码把整个DocumentSnapshot转成字符串存入列表,没法得到目标字段,该怎么修改?

当前错误代码:

val animeRef = firestoreClient.collection("Users")
animeRef.get().addOnCompleteListener { documents ->
    if (documents.isSuccessful) {
        val name = mutableListOf<String>()
        for (document in documents.result) {
            val animeId = document.toString()
            name.add(animeId)
        }
        println(name)
    }
}

方案1:提取顶层animeId字段

如果animeId是文档的顶层字段,直接用DocumentSnapshot的字段获取方法提取,同时做非空判断避免异常:

val animeRef = firestoreClient.collection("Users")
animeRef.get().addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val animeIds = mutableListOf<String>()
        for (document in task.result) {
            // 提取指定key的字段,非空时加入列表
            document.getString("animeId")?.let { id ->
                animeIds.add(id)
            }
        }
        println("提取到的animeId列表:$animeIds")
    } else {
        // 处理请求失败场景
        println("获取文档失败:${task.exception?.message}")
    }
}

方案2:提取嵌套结构中的animeId

如果animeId在文档的嵌套对象里(比如存在于animeInfo这类子Map中),先获取嵌套对象再提取字段:

val animeRef = firestoreClient.collection("Users")
animeRef.get().addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val animeIds = mutableListOf<String>()
        for (document in task.result) {
            // 先获取嵌套对象,再从中提取animeId
            val animeInfo = document.get("animeInfo") as? Map<*, *>
            val animeId = animeInfo?.get("animeId") as? String
            animeId?.let { id ->
                animeIds.add(id)
            }
        }
        println("提取到的animeId列表:$animeIds")
    } else {
        println("获取文档失败:${task.exception?.message}")
    }
}

关键说明

  • 避免直接把DocumentSnapshot转成字符串,改用getString()/get()等方法精准提取字段
  • 用?.let做非空判断,跳过不含animeId字段的文档,避免空指针异常
  • 如果animeId不是字符串类型,可对应使用getLong()/getBoolean()等类型匹配的方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:01:23