Is it possible to use Where In with a Collection Group query in Firestore?

纵然是瞬间 提交于 2021-02-11 14:00:40

问题


In my database:

-Users(Top level collection):
---user1(doc):
----------pets(sub collection):
--------------pet1(doc)
--------------pet2(doc)
---user2(doc):
----------pets(sub collection):
--------------pet3(doc)
--------------pet4(doc)

If i have a List of ids: list("pet2", "pet3", "pet4)

Is there a way to do something like this and get a back a List of DocumentsSnapshots?

firestore.collectionGruop("pets")whereIn(FieldPath.documentId(), list)

It works with a root collection but i dont know if this is possible with a collection group


回答1:


A collection group query is the only place where a filter on FieldPath.documentId() does not work the way you expect. That's because of some details about the way that this token actually works. If you try to this anyway, you will get an error like this:

Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but 'x' is not because it has an odd number of segments.

If you want to do a filter on document IDs in a collection group query, you will need to store the ID of the document as the value of a field in each document. If you use the field called "id", then you can filter on that field like this:

firestore
    .collectionGruop("pets")
    .whereIn('id', list)

This will give you a different error saying that you need to create an index, and give you a link to do so. After you create that index (it might take some time), you should be good to go.

See also: How to perform collection group query using document ID in Cloud Firestore



来源:https://stackoverflow.com/questions/61033774/is-it-possible-to-use-where-in-with-a-collection-group-query-in-firestore

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