【问题标题】:Update single value inside map in Firestore DB在 Firestore DB 中更新地图内的单个值
【发布时间】:2021-06-07 14:47:57
【问题描述】:

我有一个单位的集合,每个单位都有很多字段。其中一个字段是名为 Settings 的地图。设置为 : A->true, B->false, C->"Hello" 等。 我希望更新其中一个,假设我希望将 C 设置为“World”。

我的代码:

suspend fun updateData(unitID: String): Boolean = suspendCoroutine { cont ->
    val firestore = FirebaseFirestore.getInstance()

    firestore.collection("Units").document(unitID).get().addOnCompleteListener { it1 ->
        if (it1.isSuccessful) {
            val settings = it1.result.get("Settings") as? HashMap<String, Any>
            if (settings != null) {
                settings["C"] = "World"

                val map = hashMapOf<String, Any>()
                map["Settings"] = settings
                firestore.collection("Units").document(unitID).update(map).addOnCompleteListener { it2->
                    if (it2.isSuccessful) cont.resume(true)
                    else cont.resumeWithException(it2.exception!!)
                }
            }
        }
        else cont.resumeWithException(it1.exception!!)
    }
}

我在做什么?我正在获取地图,更新值并将其设置回来。 我的问题是,这是正确的方法吗,我可以在不先读取数据的情况下设置值吗?

【问题讨论】:

  • 请编辑您的问题并将您的数据库结构添加为屏幕截图。除此之外,您的参考资料中unitID 的值是多少?你有任何错误吗?
  • 是的,您可以在获取数据后不读取任何数据进行更新。如果您传递了正确的 UID,没有问题。@Dim

标签: android kotlin google-cloud-firestore


【解决方案1】:

无需读取即可更新数据。它将节省您的读取查询限制。所以除非有实际需要,否则不必这样做。

建议:

不要这样命名它1,它2。使用含义全名。

【讨论】:

    【解决方案2】:

    找到了:

    suspend fun updateData(unitID: String): Boolean = suspendCoroutine { cont ->
        val firestore = FirebaseFirestore.getInstance()
        val map = mapOf("Settings.C" to "World")
        firestore.collection("Units").document(unitID).update(map).addOnCompleteListener { updateData ->
            if (updateData.isSuccessful) cont.resume(true)
            else cont.resume(false)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2021-01-23
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2021-07-20
      相关资源
      最近更新 更多