'Get collection name from firebase document

Is there a way I can get the name of the collection a Firestore document is stored in based off a variable of type QueryDocumentSnapshot<DocumentData>? I'm using Firebase v9.



Solution 1:[1]

You can use .ref property of QueryDocumentSnapshot to get that document's DocumentReference and get the collection reference by using .parent as shown below:

const snap = "" // The QueryDocumentSnapshot

console.log("Collection name:", snap.ref.parent.id)

If that document is a part of sub-collection, then it'll log name of that sub-collection. You can chain .ref.parent again to get parent collection of the same.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj