पाठ 8 / 25
Modelling for Queries
Design around reads.
Denormalise and avoid unbounded growth
Firestore has no joins, and you pay per document read, so model data around the screens that read it. Denormalise: copy the few fields a list needs (author name, avatar URL) into each post, and update copies with a Cloud Function or batched write when the source changes. Keep documents bounded: an array or map that grows forever (all comments, all followers) eventually hits the document size limit and makes every read heavier, so put growing data in a subcollection or top-level collection with one document per item. Also avoid sustained high write rates to a single document (check the docs for current guidance); use counters spread across shards or aggregation instead.
Bounded versus unbounded
Document shapes, illustrative.
// risky: comments grow forever inside the post
// posts/p1
{ "title": "Hello", "comments": [ { "by": "u1", "text": "..." }, "... thousands more" ] }
// better: one document per comment, author data copied for display
// posts/p1
{ "title": "Hello", "authorId": "u1", "authorName": "Asha", "commentCount": 42 }
// posts/p1/comments/c1
{ "by": "u2", "byName": "Ravi", "text": "Nice post", "createdAt": "<server timestamp>" }List your queries first
Write down every screen and the exact query it runs before choosing collections. In Firestore, the query list is the schema.
त्वरित जाँच: Where should an ever-growing list of comments on a post live?
- In the post's title field as JSON
- In an array field on the post document
- In a subcollection with one document per comment
- In custom claims
Answer
In a subcollection with one document per comment — Documents have size limits; collections do not grow inside one document.