Irene Serrano
Irene Serrano

Reputation: 63

Android Firebase, How to check if a subcollection exists within a document

Is there a way to check whether a subcollection exists within a document for android? I need to add documents to a new subcollection just once.

Upvotes: 0

Views: 55

Answers (1)

Chen Kerry
Chen Kerry

Reputation: 11

You can use Documents getter method of FirebaseFirestore API, it is like:

public boolean isSubCollectionDocAvailable(subCollectionDocName: String) {
    AtomicBoolean isAvailable = new AtomicBoolean(false);
    FirebaseFirestore.getInstance()
            .collection("ParentCollection")
            .document("ParentDoc")
            .collection("SubCollection")
            .document(subCollectionDocName)
            .limit(1)
            .get()
            .addOnSuccessListener(result -> {
                isAvailable.set(result.exists());
            });
    return isAvailable.get();
}

And this is the database hierarchy: https://i.sstatic.net/BpQ7j.png

Upvotes: 1

Related Questions