How to group documents in Sanity - use Parent/Child relationship?
There are several ways to group documents in Sanity, and the approach you choose depends on your specific use case:
Parent/Child Relationships with References
Yes, the parent/child relationship pattern you're already using for categories is a solid approach for grouping! This involves using reference fields to create hierarchical structures. You can implement this either:
- Bottom-up: Child documents reference their parent (e.g., a blog post references its category)
- Top-up: Parent documents reference their children (e.g., a category references all its posts)
The key thing to understand is that references are bidirectional when querying with GROQ, but they only appear in the Studio UI where you define the reference field. So if you want editors to manage the relationship when editing categories, put the reference field on the category document. If it makes more sense to assign categories when editing posts, put the reference on the post.
Other Grouping Approaches
Depending on your needs, you might also consider:
Simple string fields: For basic categorization, you could use a string field with a predefined list of options. This works well when documents only belong to one group and the groups are relatively static.
Array of references: When documents can belong to multiple groups, use an array of references instead of a single reference. For example, a blog post could reference multiple category documents.
Shared field values: Sometimes you can query and group documents by any common field value (like a
categorystring field) without needing references at all.Tags/taxonomy documents: Create separate document types for tags or categories that other documents can reference, giving you more flexibility to add metadata to your groupings.
The parent/child reference pattern is definitely a versatile solution you can reuse for different grouping scenarios. The hierarchies and graphs guide has more details on modeling these relationships, and remember you can use GROQ's -> operator to traverse references in either direction when querying your content.
Show original thread9 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.