首页 > 解决方案 > 使用 Kotlin 在 Cloud Firestore 中设置数据

问题描述

我的firestore文档中有两个字段:一些评论是一个数字,评论是一个对象数组。

现在,我想在现有文档的评论数组中添加一条新评论。我知道我需要使用现有评论创建一个临时列表,然后在该列表的末尾添加一个新评论,最后,使用 Set 方法将该临时列表放入 firestore。我的问题是 - 如何做到这一点?我尝试使用下面的代码,但这只是创建了一个对象列表,但我只想要对象列表。

FirebaseFirestore.getInstance()
        .collection("name of my collection")
        .document("name of particular document")
        .get().addOnSuccessListener {

            docs: DocumentSnapshot ->

            //this creates list of list of objects
                val data = listOf(docs.data!!["comments"])

                val tempOutput = data.toMutableList()
                tempOutput.add(newCommentInfo)

               //This prints list of objects
                Log.i(TAG, "${docs.data!!["comments"]}")

               //This prints list of list of objects which I don't want
                Log.i(TAG, "$tempOutput")

                FirebaseFirestore.getInstance()
                    .collection("name of my collection")
                    .document("name of particular document")
                    .set(newCommentInfo, SetOptions.merge())

标签: androidlistarraylistkotlingoogle-cloud-firestore

解决方案


如果您只是想更新文档中的单个列表类型字段(从您的问题中并不完全清楚),使用update()方法并告诉它您正在修改哪个字段会更容易:

FirebaseFirestore.getInstance()
    .collection("name of my collection")
    .document("name of particular document")
    .update("comments", newCommentInfo)

推荐阅读