Reputation: 31
I have the following simplified data schema in Cloud Firestore:
[Users Collection]
-> "UserID1" { "displayName": "Luke", "profileImage": "someURL" }
-> "UserID2" { "displayName": "Han", "profileImage": "someURL" }
[Teams Collection]
-> "TeamId1" { "name": "Some Team Name", "members": ["UserId1", "UserId2"] }
--> [Todos Collection]
I want to show the user now all "Todo" documents of his teams and I don't know what is the best way.
1. Collection group queries - query by team ID
Two queries are needed for this. Each Todo document could have the parent team ID and be retrieved by Collection Group Query e.g. -> collectionGroup("todos").where("teamId", "in", ["teamId1", "teamId2", "teamId3"])
This looked like the best solution for me so far, but the disadvantage is that there is a limit of 10 values for the "IN" query https://firebase.googleblog.com/2019/11/cloud-firestore-now-supports-in-queries.html
2. Collection group queries - query by user-id
Here each todo document would get the user array from the team document. The query would be simple: -> collectionGroup("todos").where("members", "arrayContains", "userId1")
but you have to maintain the array after a user leaves the team e.g. or when new team members join. 3. denormalized data - each user gets a subcollection of the todos
Ok, this is a bit over the top :) and the maintenance effort is even higher than with 2.
Is there another way for data modeling or some kind of best practice for my problem?
Upvotes: 2
Views: 1223
Reputation: 138814
There is no best practice for data. You need to know that there is no "perfect", "the best" or "the correct" solution for structuring a Cloud Firestore database. However, we are usually structuring a Firestore database according to the queries that we want to perform.
So if one of the queries does the job, then you can go ahead with that. If the first one has some constraints, then use the secone one.
Upvotes: 3