android - 使用 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())
解决方案
如果您只是想更新文档中的单个列表类型字段(从您的问题中并不完全清楚),使用update()方法并告诉它您正在修改哪个字段会更容易:
FirebaseFirestore.getInstance()
.collection("name of my collection")
.document("name of particular document")
.update("comments", newCommentInfo)
推荐阅读
- html - 单个弹出窗口中的多个页面
- python - 不接受 AutoML 语言实体提取 score_threshold 作为参数
- postgresql - Postgres ECPG char[] 与 VARCHAR[]
- python - 分解出 pytest 夹具的通用设置代码
- python - 为什么深度多处理方法不更快?
- c++ - 为人工运算符重载返回引用是否有效?
- python - 如果字符串包含子字符串列表中的任何元素,如何查找字符串的起始索引
- html - 滚动时,正文一直到导航栏
- java - 如何通过 AWS Java SDK v2 中的 PutObjectRequestBuilder 添加自定义标头?
- node.js - 从 URL 检索 JSON 并使用 Cloud Functions 将其转换为 Cloud Firestore 集合