Home > front end >  How do I check if collection exist in firestore (not document) in JS
How do I check if collection exist in firestore (not document) in JS

Time:07-14

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!

CodePudding user response:

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
}

CodePudding user response:

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.

  • Related