skip to Main Content

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

2

Answers


  1. This can be done with a simple get() query. For a more complex retrieval of a document like listening to live updates and performing filter operations please refer to the Firebase documentation.

    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)
            }
    
    Login or Signup to reply.
  2. 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!
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search