11

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
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Ashton
  • 1,265
  • 14
  • 23

1 Answers1

16

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.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • 1
    Thanks very much, I'm not sure how I missed this in the docs. Exactly what I was looking for! – Ashton Apr 04 '20 at 09:46