Home > Software design >  Fetch Single Document from Firestore
Fetch Single Document from Firestore

Time:09-01

I switched my database data from the Real-time Database to Firestore because I need more defined querying when it comes to my apps that I'm building. However, I'm needing a little bit of help because I'm trying to assign the values to the currentCustomer variable, but instead of putting snapshot.child()..., what do I need to do with document? Thank you!

My Firestore Document

enter image description here

MyUtil.kt

var currentCustomer: Customer? = null

        fun fetchCurrentCustomer() {

            val uid = FirebaseAuth.getInstance().uid
            val ref = FirebaseFirestore.getInstance().collection("/$REF_CUSTOMERS/$uid")

            ref.get().addOnSuccessListener { document ->
                if (document != null) {
                    currentCustomer = Customer(
                        document.documents.,
                        snapshot.child("fullname").getValue(String::class.java)!!,
                        snapshot.child("username").getValue(String::class.java)!!,
                        snapshot.child("email").getValue(String::class.java)!!,
                        "",
                        snapshot.child("profileImageUrl").getValue(String::class.java)!!
                    )
                }
            }

         }

CodePudding user response:

Try this to fetch a single document from firestore collection

val reference = FirebaseFirestore.getInstance()
                            .collection("REF_CUSTOMERS")
                            .document($uid)
    
     reference.get().addOnSuccessListener { document ->
                    if (document != null) {
                           currentCustomer = document.toObject(Customer::class.java
                    }
                }
  • Related