Home > Enterprise >  How To Find Any Value in Fire store
How To Find Any Value in Fire store

Time:01-12

I Have the same key M6LMD0D7oyW1ueNKU2c6sXcZZFd2 I just want to check if this is present or not in Firestore. How can I do this?

enter image description here

CodePudding user response:

This can be done with a simple get() query

val docRef = db.collection("users").document(user.userId) // Access userId    

docRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: ${document.data}")
            } else {
                Log.d(TAG, "No such document")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "get failed with ", exception)
        }

CodePudding user response:

To check if a particular user (document) exists in a collection in Firestore, you can simply use a get() call and attach a complete listener. In code, it will be as simple as:

val uid = Firebase.auth.currentUser?.uid
val uidRef = Firebase.firestore.collection("users").document(uid)
uidRef.get().addOnCompleteListener {
    if (it.isSuccessful) {
        val document = task.result
        if (document.exists()) {
            Log.d(TAG,"The user already exists.")
        } else {
            Log.d(TAG, "The user doesn't exist.")
        }
    } else {
        task.exception?.message?.let {
            Log.d(TAG, it)  //Never ignore potential errors!
        }
    }
}
  • Related