Firestore-获取子集合的父文档 [英] Firestore - get the parent document of a subcollection
问题描述
我正在使用一个使用以下层次结构的Firestore数据库的应用程序: parent_collection: parent_document: 子集合: child_document { 字符串名称} 使用collectionGroup,我已经能够查询子集合中具有特定名称的文档,但是我不知道如何获取parent_document
I'm working on an app that uses a firestore database with the following hierarchy: parent_collection: parent_document: subcollection: child_document{ string name} using collectionGroup I've been able to query subcollection for documents with a certain name, but I don't know how to get the parent_document
db.collectionGroup("subcollection").whereEqualTo("name", searchText).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
//here I want to get the parent id of all results
}
}
});
实现此目标的最佳方法是什么?
What is the best way to achieve that?
推荐答案
QuerySnapshot
指向许多QueryDocumentSnapshot
实例.
通过QueryDocumentSnapshot
,您可以通过以下方式获取其来源:
From a QueryDocumentSnapshot
, you can get the collection it's from with:
snapshot.getRef().getParent()
然后父级DocumentReference
是:
snapshot.getRef().getParent().getParent()
因此要获取父文档的子集,请执行以下操作:
So to get a subscollection of the parent document with:
snapshot.getRef().getParent().getParent().collection("name_of_subcollection")
是的,我同意...这本来应该更具可读性. :)
Yes, I agree... that could've been a bit more readable. :)
这篇关于Firestore-获取子集合的父文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!