Apri
Apri

Reputation: 1515

Firestore: Check if virtual document exists

I am developing an android app, where users can register. To save user data, I user Firebase Firestore. So, When a user registers, a document with the FirebaseUser.userId as id get created.

val exampleObject = ExampleObject(exampleData1, exampleData2)
val firestoreUser = FirebaseAuth.getInstance().currentUser
firebaseFirestore
   .collection("users")
   .document(firestoreUser.uid)
   .collection("exampleCollection")
   .document("exampleDocument")
   .set(exampleObject)

The document that gets created for each user only contains collections, therefore, Firestore does only create a "dummy document". So, how can I check if this document exists or not?

firebaseFirestore
    .collection("users")
    .document(firestoreUser.uid)
    .get()
    .addOnSuccessListener { doc->
        if(doc.exists()) {

        } else {

        }
    }

This does not work, because it is only a "dummy document", that does not really exist

Upvotes: 3

Views: 2072

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Firestore does only create a "dummy document".

It does not create any document. That document does not exist because you didn't create it at all. What you did do, was only to create a subcollection under a document that never existed. In other words, you just reserved an id for a document in a collection and then you created a subcollection under it.

One thing to remember, in Cloud Firestore documents and subcollections don't work like filesystem files and directories. If you create a subcollection under a document, it does not implicitly create any parent documents. Subcollections are not tied in any way to a parent document.

So note that there is no physical document at that location but there is other data under the location, which is the exampleCollection subcollection. Remember that the "dummy document" that you are talking about becomes a real document only when you write at least a property that can hold a value in it.

So in your case, the following statement:

if(doc.exists())

Will be always evaluated to false.

Upvotes: 5

Related Questions