I have been following along the following document: https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query
My data structure roughly looks like this:
/teams/{teamid}
{
displayName: "Company X Team",
owner: "userid",
}
/teams/{teamid}/invites/{emailAddressAsKey}
{
someProp: "my data"
}
In my web app I want to search through all the different teams records to find an invite who's id/key is equal to the email address that I pass in. After reading through the documentation, I think a Collection Group Query is what I'm looking for. However, my situation doesn't exactly match the example. I want to match on the key, not a prop within the document. I suppose I could add the email address again as a prop, but that doesn't feel right.
You have to put the document ID as a key in the document itself. There is currently no other solution.
It's tempting to use FieldPath.documentId()
in a where
clause (eg following Alex Mamo's answer https://stackoverflow.com/a/56967352/2518722), but that doesn't work in the general case. The reason is that FieldPath.documentId()
actually refers to the full, unique ID of the document including its path.
If you do try this you'll get the following error:
Error: When querying a collection group and ordering by FieldPath.documentId(), the corresponding value must result in a valid document path, but '<your doc id>' is not because it contains an odd number of segments.
Basically the where
clause only works with searches on keys/values not document IDs.
You can solve this with the help of FieldPath.documentId()
like in the following line of code:
db.collectionGroup('teams').where(firebase.firestore.FieldPath.documentId(), '==', 'teams/teamId').get()
This query will return all documents with a specific team id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With