skip to Main Content

Hoi, I would like to check, using React javascript, if a collection in the Firestore already exists, no matter if it’s empty or not. I tried:

if (collection(db, ref)) // is always true somehow

Any ideas? Thanks!

3

Answers


  1. You would need to try to fetch from the collection and see if anything is returned:

    const snap = await query(collection(db, ref), limit(1));
    if (snap.empty) {
      // no docs in collection
    }
    
    Login or Signup to reply.
  2. There is no function available in the SDK that can help you can check if a particular collection exists. A collection will start to exist only if it contains at least one document. If a collection doesn’t contain any documents, then that collection doesn’t exist at all. So that being said, it makes sense to check whether a collection contains or not documents. In code, it should look as simple as:

    const snapshot = await query(collection(db, yourRef), limit(1));
    if (snapshot.empty) {
      //The collection doesn't exist.
    }
    

    One thing to mention is that I have used a call to limit(1) because if the collection contains documents, then we limit the results so we can pay only one document read. However, if the collection doesn’t exist, there is still one document read that has to be paid. So if the above query yields no resul## Heading ##t, according to the official documentation regarding Firestore pricing, it said that:

    Minimum charge for queries

    There is a minimum charge of one document read for each query that you perform, even if the query returns no results.

    Login or Signup to reply.
  3. You have to fetch the collection out of the database and check if it has more than 0 documents. Even, if the collection doesn’t exist, it will return 0.

    const db = firebase.firestore();
    db.collection("YOUR COLLECTION NAME").get().then((res) =>{
         if(res.size==0){
              //Collection does not exist
         }else{
              //Collection does exist
         }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search