Firebase Collection Group Query on Id / Key

不想你离开。 提交于 2020-02-03 13:57:28

问题


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.


回答1:


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(), '==', 'teamId').get()

This query will return all documents with a specific team id.




回答2:


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.



来源:https://stackoverflow.com/questions/56963797/firebase-collection-group-query-on-id-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!