27
votes

So few day ago I moved my apps posts to cloud firestore from realtime database because of the more flexable querying that firestore apparently has. I have been modifying my code to work with firestore as the new database. Now I ran into a problem. How can I retrieve every document within "Posts" collection that has "Likes" collection that contains a specifically named document? I don't know if that makes sense so here's an image showcasing the problem:

enter image description here

I had a working query for firebase realtime database but can't figure out how to do it with firestore. Is it possible or do I have to change the structure of my database? If I do have to change the structure, what would be the most convenient way of getting the same result?

1
There are very clear document for query. You have to search hereBlackBlind
Yes, I did read everything I could find but didn't figure it out.Aapo Vainonen
@AapoVainonen What do you mean by "that contains a specificaly named document"? The doc in the Likes collection has a specific field value? A specific doc id?Renaud Tarnec
What I mean by that is for example how to retreive every post that specific user has liked. So in this example check if "Likes" collection contains that users user id that we want to see the liked posts of. Sorry if that doesn't make sense english isn't my native language.Aapo Vainonen
So in the document yQ6m2... (in the Likes collection) there is a field named for example likerand you want to search for the docs that have a certain value for this field. right?Renaud Tarnec

1 Answers

27
votes

This is currently not possible with collection group queries. You might be tempted to put a filter on the query for FieldPath.documentId() == 'your-doucment-id', but that just isn't supported. FieldPath.documentId() is actually a token that refers to to fully unique document id, which includes the entire path of the document.

The workaround is to store the document ID as a field in the document, and filter on the contents of that field instead. So, if the document had a field called id with the ID of the document, you could query for collectionGroup("Likes").whereEquals('id', 'your-document-id').