Home > Enterprise >  How to get the root document which a subcollection document belongs to?
How to get the root document which a subcollection document belongs to?

Time:11-29

After getting a snapshot for a particular document in a subcollection, I would like to get the associated data to the root document which it belongs to.

For example, there is a collection restaurants and each one has a products subcollection.
After searching for a particular product of a restaurant, how can I get the restaurant data which the product belongs to? Do I need to make another search or how can I get it from the product snapshot?

QuerySnapshot snapshot = await FirebaseFirestore.instance
    .collectionGroup('products').get();

QueryDocumentSnapshot product = snapshot.docs.elementAt(0);

CodePudding user response:

There's actually a very easy way to do this, and it takes advantage of the ref.path of the document. You can split the ref.path string into it's component sections - remember, it's the full "/" separated path to the document, so for example:

restaurants/{restaurantId}/products/{productId}
topCollection/{topdocumentId}/nextCollection/{nextDocumentId}/.../bottomCollection/{bottomDocumentId}

Clearly, the first two segments are the path to the "parent" document - regardless of the depth of the tree (I happen to have a very deep tree structure). You can then fetch the "top parent":

db.collection(restaurants).doc(topdocumentId).get()

CodePudding user response:

To find the parent/restaurant document for product, you'll want to walk up the reference/parent chain:

var restaurantRef = product.reference.parent.parent;

You will still need to get that document with:

var restaurantDoc = await restaurantRef.get();
  • Related