Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Collection Group Query on Id / Key [duplicate]

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.

like image 841
Scott Dietrich Avatar asked Jul 10 '19 05:07

Scott Dietrich


2 Answers

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.

like image 118
HughHughTeotl Avatar answered Nov 17 '22 16:11

HughHughTeotl


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.

like image 29
Alex Mamo Avatar answered Nov 17 '22 16:11

Alex Mamo