问题描述
我正在开发一个应用程序,该应用程序使用具有以下层次结构的 Firestore 数据库:parent_collection:父文档:子集:子文档{字符串名称}使用 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 - 获取子集合的父文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!