4

How can I check if a collection exists or not in firestore?

There is a method to check document exist. Such as:

this.afs.doc('users/' + userId).ref.get().then((doc) => {
    if (doc.exists) {
        console.log("User alread exists")
    } else {
        console.log("User first login")
    }
}).catch(function (error) {
    console.log("Error getting document:", error);
});

But I could not find a method to check the collection. In my case, I don't know if any document exists. So, I cannot use

this.afs.doc

to get the document. I want to check the root collection existence.

ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
lei lei
  • 1,753
  • 4
  • 19
  • 44
  • 2
    Possible duplicate of [Is possible to check if a collection or sub collection exists?](https://stackoverflow.com/questions/47997748/is-possible-to-check-if-a-collection-or-sub-collection-exists) – André Kool Aug 14 '18 at 09:52
  • 1
    I have read it. but it is checking sub collection existence. doesn't apply for my question. – lei lei Aug 14 '18 at 09:54

1 Answers1

1

The solution presented in the "duplicate" page works.

If you want to know if a collection is empty, you have to run a query on that collection, get the document snapshots and then check if the snapshot is empty.

Say you have a CollectionReference called reference;

First run a collection Query on Reference and retrieve the snapshot - whether it exists or not, this method will produce a result:

reference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            if(queryDocumentSnapshots.isEmpty()){
                        
                Toast.makeText(getActivity(), "Collection is Empty", 
                Toast.LENGTH_LONG).show();
            }
        }
});
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
matshidis
  • 489
  • 5
  • 11