简体   繁体   中英

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.

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.stack.imgur.com/BpQ7j.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM