我的Firestore数据库中具有以下结构:几个UserLists
集合,其中包含Users
。每个用户可能有一个Notes
子集合。
我正在做一个效果很好的子集合组查询,从Notes子集合中返回注释。
我的问题是,从Notes子集合中检索的Note文档中,我可以获得父文档ID吗?在下面的示例中,该用户为User 1。使用JavaScript。
Collection: UserList 1
Doc: User 1
Subcollection: Notes
Doc: Note 1
Collection: UserList 2
Doc: User 1
Subcollection: Notes
Doc: Note 1
答案 0 :(得分:2)
您可以使用以下方法之一:
const query = ......;
query
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.ref.path);
console.log(doc.ref.parent.parent.id);
});
})
在每个QueryDocumentSnapshot
上,您可以使用ref
属性,该属性返回一个DocumentReference
。然后,在此DocumentReference
上使用path属性,该属性将返回完整路径,例如UserList1/User1/Notes/Doc1
。
或者您使用DocumentReference
的{{3}}属性,该属性返回一个parent
,然后再次使用CollectionReference
的{{3}}属性时间)以获取父项DocumentReference
,然后获取该父项id
的{{1}}属性。