Auto-populating array of references to child documents in Sanity
Based on what you're describing, there are a couple of approaches to solve this problem, though auto-populating parent references isn't the typical pattern in Sanity.
The Reverse Reference Pattern (Recommended)
Instead of auto-populating references in the parent document, I'd recommend structuring your schema so that children reference their parent. Then you can query all children for a given parent using GROQ. This is the most common pattern because:
- Children naturally "know" their parent
- You avoid the complexity of auto-population
- Users can still manually sort the children
Here's how it works:
Child schema:
{
name: 'child',
type: 'document',
fields: [
{
name: 'parent',
type: 'reference',
to: [{type: 'parent'}]
},
{
name: 'orderRank',
type: 'string',
hidden: true
}
// other fields
]
}Query to get sorted children:
*[_type == "parent" && _id == $parentId][0] {
...,
"children": *[_type == "child" && parent._ref == ^._id] | order(orderRank)
}For manual sorting, use the Orderable Document List plugin which provides drag-and-drop ordering functionality in Studio using the orderRank field.
Auto-Population with Sanity Functions
If you really need the parent to contain an array of child references, you can use Sanity Functions to automatically update the parent when children are created. Functions are Sanity's modern, serverless compute solution that runs directly on Sanity's infrastructure - no external hosting needed.
You'd set up a Function that:
- Listens for document create/delete events on child documents
- Updates the parent's reference array accordingly
- Maintains the
orderRankfor sorting
However, this approach has downsides:
- More complexity
- Potential for race conditions
- You need to handle edge cases (what if the function fails?)
The Array-in-Parent Approach
A third option is to manually manage references in the parent, but make it less tedious:
{
name: 'parent',
type: 'document',
fields: [
{
name: 'children',
type: 'array',
of: [{
type: 'reference',
to: [{type: 'child'}]
}]
}
]
}The array itself is drag-and-drop sortable in Studio, so users can reorder as needed. While they need to manually add children, this gives them complete control over which children appear and in what order.
For your use case, I'd strongly recommend the reverse reference + Orderable Document List approach - it's cleaner, more maintainable, and gives users the sorting control they need without manual reference management.
Show original thread1 reply
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.