【问题标题】:Kotlin Save Firestore query result for a variableKotlin 保存变量的 Firestore 查询结果
【发布时间】:2021-06-22 20:24:10
【问题描述】:

我对 Firebase 有疑问。 我还在网站和 Kotlin 应用中使用 Firestore。

在网站上,我可以通过以下方式将查询结果保存到变体中:

const addStudentManu = async($this) => {
 const userId = await db.collection('users').where('neptun','==',ASD123).get();
 const getUserId = userId.docs.map(doc=>doc.id);
}

我如何在 kotlin 中做到这一点?

【问题讨论】:

    标签: firebase kotlin google-cloud-firestore


    【解决方案1】:

    事情是这样的:

    db.collection("users")
            .whereEqualTo("neptun", "ASD123")
            .get()
            .addOnSuccessListener { documents ->
                val list = mutableListOf<String>()
                for (document in documents) {
                    Log.d(TAG, "${document.id}")
                    list.add(document.id)
                }
                println(list)
            }
            .addOnFailureListener { exception ->
                Log.w(TAG, "Error getting documents: ", exception)
            }
    

    您可以查看documentation中的示例代码sn-ps。

    【讨论】:

      【解决方案2】:

      虽然@Dharmaraj 的答案可以很好地工作,但对于 Kotlin,保存查询结果最方便的方法是使用 Kotlin Coroutines,我们可以创建一个挂起函数并将所有文档映射到它们对应的ID,与您的示例类似。所以请尝试以下代码行:

      private suspend fun getIdsFromFirestore(): List<String> {
          val ids = db.collection("users").whereEqualTo("neptun", "ASD123").get().await()
          return ids.documents.mapNotNull { doc ->
              doc.id
          }
      }
      

      如您所见,我们现在有一个名为await() 的扩展函数,它将中断协程,直到数据库中的数据可用,然后返回。这与在网络上使用 async 时几乎相同。

      现在我们可以简单地从另一个挂起方法调用它,如以下代码行:

      private suspend fun getIds() {
          try {
              val ids = getIdsFromFirestore()
              // Do what you need to do with the list of IDs
          } catch (e: Exception) {
              Log.d(TAG, e.getMessage()) //Don't ignore potential errors!
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-19
        • 2021-10-25
        • 2021-03-01
        • 2016-04-18
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多