I have the following structure in my Firestore DB: several UserLists collections, which hold the Users. Each user may have a Notes subcollection.
I'm doing a subcollection group query that works well, returning notes from across the Notes subcollection.
My question is, from the Note document retrieved from the Notes subcollection, can I get the parent document ID? That would be User 1 in the below example. Using JavaScript.
Collection: UserList 1
Doc: User 1
Subcollection: Notes
Doc: Note 1
Collection: UserList 2
Doc: User 1
Subcollection: Notes
Doc: Note 1
You could use one of the following approaches:
const query = ......;
query
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.ref.path);
console.log(doc.ref.parent.parent.id);
});
})
On each QueryDocumentSnapshot, you can use the ref property, which returns a DocumentReference. Then, on this DocumentReference you use the path property, which will return the full path, e.g. UserList1/User1/Notes/Doc1.
Or you use the parent property of the DocumentReference, which returns a CollectionReference, then you use again the parent property (of the CollectionReference this time) to get the parent DocumentReference and then the id property of this parent DocumentReference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With