Chance
Chance

Reputation: 17

How to get the keys in a Firestore document?

enter image description here

Hello, this is Kotlin Beginner.

While playing with Firestore, I suddenly had a question.

The value of a field can be easily retrieved, but

Is there a way to get the text of the field itself?

I would like to take the blue square in the following image literally.

Any help would be appreciated.

Upvotes: 0

Views: 410

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

DocumentSnapshot#getData() method, returns an object of type Map<String!, Any!>. To get the keys of a document, simply iterate through the Map object, as explained in the following lines of code:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseFirestore.getInstance()
val uidRef = rootRef.collection("users").document(uid)
uidRef.get().addOnSuccessListener { document ->
    if (document != null) {
        document.data?.let { data ->
            data.forEach { (key, _) ->
                Log.d(TAG, key)
            }
        }
    } else {
        Log.d(TAG, "No such document")
    }
}.addOnFailureListener { exception ->
    Log.d(TAG, "get failed with ", exception)
}

To obtain the following result in the logcat:

email
id
nickname
password
phone

Upvotes: 1

Related Questions