How do I check if a document exists in the Firestore?

Asked 2 years ago, Updated 2 years ago, 88 views

How do I check if the document exists in the Firestore?

The language is Kotolin.

firebase kotlin

2022-09-30 15:34

1 Answers

You can check it from exists() in DocumentSnapshot.If the Document does not exist, you can also use getData() to return null, so you can decide from that.

If the DocumentSnapshot points to an non-existing document, getData() and its correcting methods will return null. You can always explicitly check for a document's presence by calling exists().

val docRef=db.collection("cities").document("SF")
docRef.get()
        .addOnSuccessListener { document->
            if(! document.exists()) {
                Log.d(TAG, "DocumentSnapshot data:${document.data}")
            }
            ...
        }
        .addOnFailureListener {exception->
            ...
        }
}


2022-09-30 15:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.