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)
}
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!
}
}
}
2
Answers
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.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: