Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore get subcollection parent document ID - JavaScript

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
like image 687
Ashton Avatar asked Apr 03 '20 11:04

Ashton


1 Answers

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.

like image 157
Renaud Tarnec Avatar answered Sep 22 '22 15:09

Renaud Tarnec