Firebase 和 Kotlin:获取文档问题的 id

机会

我在使用 Firebase 和 Kotlin 时遇到了一个有趣的问题。

val docRef = db.collection("Year")
            .document(DB_year.toString())
            .collection("Month")
            .document((DB_month+1).toString())
            .collection("Day")
            .document(today)
            .collection("write")
            .get()
            .addOnSuccessListener { result ->

                for(document in result) {
                    println("document_id : " + document.id)
                }

            }

如果用这个code获取document id,就可以正常获取了。

在此处输入图片说明

enter code here

此代码无法获取文档 ID。

        val docRef = db.collection("Year")
            .document(DB_year.toString())
            .collection("Month")
            .document((DB_month+1).toString())
            .collection("Day")
            .get()

为什么会这样?

  • 我的 Firestore 收藏

在此 输入图片说明 在输入图片说明

雷诺塔内克

在此处输入图片说明

如上面的 Firebase 控制台屏幕截图所示,Day集合中的文档在Firebase 控制台中以斜体显示:这是因为这些文档(在控制台中)仅作为一个或多个子集合的“容器”存在,但是不是真正的文件

如果直接在write具有完整路径集合下创建文档Year/docYear1/Month/subDocMonth1/Day/subDcoDay1/write/writeDoc,则不会创建中间文档(即MonthDay集合中没有文档)。

Firebase 控制台以斜体显示这种“容器”(或“占位符”),以“具体化”层次结构并允许您导航到write文档,但该Day文档在 Firestore 数据库中不存在。因此,您的第二个查询的结果为空

有关更多详细信息,请参阅此答案


请注意,如果你想获得父IDS(文档和集合)的写入集合中的文档,你可以使用parent的特性DocumentReferenceCollectionReference

因此,您可以执行以下操作:

db.collection("Year")
        .document(DB_year.toString())
        .collection("Month")
        .document((DB_month+1).toString())
        .collection("Day")
        .document(today)
        .collection("write")
        .get()
        .addOnSuccessListener { result ->

            for(document in result) {
                println("Day_doc_id : " + document.reference.parent.parent?.id)
            }

        } 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章