Shivam Sahil
Shivam Sahil

Reputation: 4921

Cloud Firestore: Get Value from collection ID if it exists

I want to obtain the value of a collection ID from a collection in cloud firestore if it exists:

export const getSlugs = async () => {
  const document = await db
    .doc(constDocumentRefs.slugs)
    .collection('<collection_id>')

    
  
  return ;
};

but this returns me collection reference, I can check if its empty by calling: document.get().empty method but not sure how do I get the value of collection, in case it is not empty.

My collection looks like this:

{
    key1:1
    key2:2
}

I want to keep it like return the actual value if collection exists otherwise return -1. Someone please help!

Upvotes: 0

Views: 110

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

I can see two possible ways:

From the front-end:

As Dharmaraj mentioned in his comment, you need to fetch document(s) in the collection to see if the querySnapshot is empty or not. If the snapshot is empty, the collection does not exist. You can limit the query to only one document to minimize cost. For that you'll use the limit() method. And for checking if the QuerySnapshot contains a doc use the size property.

From a back-end:

The Admin SDKs offer a specific method to list collections, for example listCollections() for the Node.js Admin SDK (and listCollections() method of a DocumentReference for listing sub-collections). You can implement that in a Cloud Function and call it from your front-end: I wrote an article on this approach.

Upvotes: 1

Related Questions