Firestore get subcollection parent document ID - JavaScript

落爺英雄遲暮 提交于 2021-02-08 10:19:21

问题


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

回答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.



来源:https://stackoverflow.com/questions/61011280/firestore-get-subcollection-parent-document-id-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!