【问题标题】:How can I get one field on Firebase Firestore?How can I get one field on Firebase Firestore?
【发布时间】:2022-12-01 22:27:02
【问题描述】:

Hello friends I'm doing practice about Firestore and Firebase Auth and I wanted to read only one field but I can't do that. It's probably easy but I can't find anything in Internet. Is anyone can help me. Have a good Codes :)


A piece of my code



auth = Firebase.auth

private val db = Firebase.firestore.collection("user")


private fun getPic(){
val pic = db.document(auth.currentUser?.email.toString()).get(..?.) ....?..
}


I wanted to read that URL

【问题讨论】:

    标签: android firebase kotlin google-cloud-firestore


    【解决方案1】:

    There is no way to fetch just one field from a Firebase document (https://stackoverflow.com/a/48312562/1896015).

    You need to fetch the whole document, which is done asynchronously and then handle the received response, which contains the whole document data.

    You also fetch the document from the collection which in this case is user which makes the whole path user/{email}.

    From your code example this would probably look like this:

    private fun getPic() {
     val docRef = db.collection("user").document(auth.currentUser?.email.toString())
     docRef.get()
            .addOnSuccessListener { document ->
                if (document != null) {
                    Log.d(TAG, "picUrl: ${document.data.picUrl}")
                } else {
                    Log.d(TAG, "No such document")
                }
            }
            .addOnFailureListener { exception ->
                Log.d(TAG, "get failed with ", exception)
            }
    }
    

    In this case you only log the information, but I guess you would want to return the picUrl from the function. I suggest looking in to Kotlin asynchronous functions for different ways to handle this: https://kotlinlang.org/docs/async-programming.html#callbacks

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2022-11-20
      • 2022-12-28
      • 2022-12-26
      • 2022-12-27
      • 2022-12-27
      • 2022-12-26
      • 1970-01-01
      • 2022-12-19
      相关资源
      最近更新 更多