Firestore-获取子集合的父文档

The*_*ior 7 android firebase google-cloud-firestore

根据要求我的数据库的屏幕截图我正在使用一个使用以下层次结构的Firestore数据库的应用程序:parent_collection:parent_document:子集合:child_document {字符串名称}使用collectionGroup我已经能够查询子集合中具有特定名称的文档,但是我没有知道如何获取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
                        }
                    }
                });
Run Code Online (Sandbox Code Playgroud)

做到这一点的最佳方法是什么?

Fra*_*len 8

QuerySnapshot点到了一些QueryDocumentSnapshot实例。

从中QueryDocumentSnapshot,您可以获取其来源:

snapshot.getRef().getParent()
Run Code Online (Sandbox Code Playgroud)

然后父级DocumentReference是:

snapshot.getRef().getParent().getParent()
Run Code Online (Sandbox Code Playgroud)

因此,要获得父文档的子集合,请执行以下操作:

snapshot.getRef().getParent().getParent().collection("name_of_subcollection")
Run Code Online (Sandbox Code Playgroud)

是的,我同意...这本来应该更具可读性。:)

  • 它在JavaScript中应该非常相似。类似于`snapshot.ref.parent.parent.collection(“ name_of_subcollection”)`。从[`DocumentSnapshot`](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot)开始,主要是遵循参考文档中的跟踪记录。如果您很难使它起作用,则可能需要发布新问题以显示您尝试过的操作(请参阅[如何创建最小,完整,可验证的示例](http://stackoverflow.com/help/mcve) ),然后链接回该问题/评论以供参考。 (2认同)