How to perform dynamic where queries with firestore and add indexes

£可爱£侵袭症+ 提交于 2020-08-04 05:14:50

问题


In my site i am conducting a survey like tests, each test has attendies sub collection look like this

When someone finishes a test i also add their uid to completed field like i drawn in the box. Now i want to query tests based on status == completed.

Here is what i tried

    this.completedModulesRef$ = this.afs.collection('tests', ref => 
           ref.orderBy('moduleNum', 'desc')
              .where('completed.'+auth.uid+'.status','==','completed'));

    this.completedModules$ = this.completedModulesRef$.valueChanges();

Then firestore asked me to add indexes, when i follow the generated link to add indexes i got this

which is pointing to completed.CurrentUserId.status. I believe this only work for current user.

I have few question

1) .where('completed.'+auth.uid+'.status','==','completed') Is this a valid query?

2) If yes how can i index it?

3) Any way to query the top collections based on sub collection value?. (this is what i really want)

Any help appreciated.


回答1:


You could just instead use an array of objects (each object represents one attendie) to track all the completed attendies. Arrays are indexed in firestore.

The data structure of the array would be:

compeleted: [{}] = [
  {id: string, points: number, status: string}
]

This might not be the most optimal database model depending on how and where you want to fetch the data but it will be indexed and you will be able to query it. I would consider storing the points and status in the subcollection of attendies. Have a look at grouped collection queries in firestore - new feature where you can query across all attendies subcollections at once - for any attendie with a certain id and a status of complete if you want to fetch all the tests that one attendie completed.



来源:https://stackoverflow.com/questions/48386762/how-to-perform-dynamic-where-queries-with-firestore-and-add-indexes

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