问题
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