我的 Firestore 数据库中有以下结构:几个 UserLists
收藏,其中包含 Users
.每个用户可能有一个 Notes
子集。
我正在执行一个运行良好的子集合组查询,返回来自 Notes 子集合的注释。
我的问题是,从 Notes 子集合中检索到的 Note 文档,我可以获得父文档 ID 吗?这将是下面示例中的用户 1。使用 JavaScript。
Collection: UserList 1
Doc: User 1
Subcollection: Notes
Doc: Note 1
Collection: UserList 2
Doc: User 1
Subcollection: Notes
Doc: Note 1
最佳答案
您可以使用以下方法之一:
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
.或者您使用
parent
DocumentReference
的属性(property),返回 CollectionReference
,然后您再次使用 parent
属性(这次是 CollectionReference
)来获取父级 DocumentReference
然后是 id
此父项的属性 DocumentReference
.
关于firebase - Firestore 获取子集合父文档 ID - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61011280/