Heng YouSour
Heng YouSour

Reputation: 153

Get parent collection & sub collection document on firebase

I'm new to firebase I had 2 collection categories & products and the product collection, has a sub-collection Category, how can I get all documents from the product collection and sub-collection category? thank in advance enter image description here

Upvotes: 1

Views: 1333

Answers (2)

Nishant Mishra
Nishant Mishra

Reputation: 1

const subCategory = await getFirestore()
  .collectionGroup("subCategory")
  .get();

  if(!subCategory.empty){
    subCategory.forEach(async (doc) => {
     let parent = await doc.ref.parent.parent.get();
      console.log("parent",parent.data());
      console.log("child",doc.data());
    })
  }`

This will get you all the subcollection and parent collection data.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

There is no way to read from both the parent collection and the sub collection in one operation. Read always come from one (type of) collection, which is sometimes explained as "all reads in Firestore are shallow".

You can either:

  • Read the parent collection, and then for each (relevant) document read its subcollection as a separate operation.
  • Read the parent collection, and read all SubCategory collections in one go with a collection group query.

The second approach performs fewer calls to the server, but has a higher chance of reading more documents than needed, if (for example) you may not want the SubCategory collection from some documents.

Upvotes: 3

Related Questions