问题
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