Issue
I am trying to check if a document exists in Firestore. But I am getting the wrong result when I try to run the code. This is my code. Actually, there is no document corresponding to the document named currentUse
in the collection. But I get that task is successful and Toast message appears as the document exists. Where might have I gone wrong and how to check a document exists in Kotlin.
val currentUse= FirebaseAuth.getInstance().currentUser?.uid
private val mFireStore = FirebaseFirestore.getInstance()
val docref =mFireStore.collection("Users").document("$currentUse")
docref.get().addOnCompleteListener { task ->
if (task.isSuccessful){
Toast.makeText(applicationContext,"Exists",Toast.LENGTH_SHORT).show()
startActivity(Intent(applicationContext, MainActivityUser::class.java))
}
}
Solution
Actually there is no document corresponding to the document named currentUse in the collection. But I get that task is successful and the Toast message appears as the document exists.
If you only check if a Task is successful it doesn't mean that the document where the reference is pointing to actually exists. It means that your get() call is completed with no errors.
To check if a particular document exists, you should explicitly call exists() on the DocumentSnapshot object. So please use the following lines of code:
docref.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val document = task.result
if(document != null) {
if (document.exists()) {
Log.d("TAG", "Document already exists.")
} else {
Log.d("TAG", "Document doesn't exist.")
}
}
} else {
Log.d("TAG", "Error: ", task.exception)
}
}
Answered By - Alex Mamo