Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - get the parent document of a subcollection

Screenshot of my database as requestedI'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?

like image 275
The Forgotten Warrior Avatar asked May 20 '19 10:05

The Forgotten Warrior


People also ask

How do you access Subcollection in firestore?

You can either go to Firestore Databases > Indexes console and do it, or use the firebase cli. But the easiest option is to just let your code (that performs the query) run and firestore will automatically error out when an index is missing.

How do I get data from QueryDocumentSnapshot?

A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).

How do I get specific data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

Can you have a collection in a collection firestore?

A collection contains documents and nothing else. It can't directly contain raw fields with values, and it can't contain other collections. (See Hierarchical Data for an explanation of how to structure more complex data in Cloud Firestore.)


1 Answers

The QuerySnapshot points to a number of QueryDocumentSnapshot instances.

From a QueryDocumentSnapshot, you can get the collection it's from with:

snapshot.getRef().getParent() 

And then the parent DocumentReference is:

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. :)

like image 73
Frank van Puffelen Avatar answered Sep 17 '22 13:09

Frank van Puffelen