Auto-populate reference array based on reverse relationship in Sanity
Based on what you're describing, it sounds like you want to automatically show which products belong to a category, rather than manually maintaining an array of references. The good news is you don't need to store this in your category document at all - you can use GROQ's references() function to dynamically find all products that reference a specific category!
The Schema Setup
First, make sure your product schema has a reference to the category:
// product.js
{
name: 'product',
type: 'document',
fields: [
{
name: 'title',
type: 'string'
},
{
name: 'category',
type: 'reference',
to: [{type: 'productCategory'}]
}
// other fields...
]
}Querying Products by Category
Instead of maintaining an array in the category document, you can query for products that reference the category using the references() function:
*[_type == "productCategory" && slug.current == "vinyl-window"][0]{
_id,
title,
"products": *[_type == "product" && references(^._id)]{
title,
price,
// other fields you want
}
}The key here is references(^._id) - this finds all products that contain a reference to the current category's ID. The ^ operator accesses the parent document's ID within the subquery.
Why This Approach is Better
Rather than storing an array of references in your category document (which would require manual maintenance), this approach:
- Automatically shows all products in a category based on the product's category field
- Maintains a single source of truth (the product's category field)
- Avoids data duplication and sync issues
- Makes it easier to change a product's category
If You Really Need the Array in Studio
If you specifically want to see this list in the Studio UI when editing a category, you could create a custom component that displays the products, but the data itself shouldn't be stored as an editable array - it should be computed from the references.
The validation section you found is for validating user input, not for auto-populating fields based on relationships. The references() function in GROQ is the right tool for what you're trying to accomplish!
Show original thread2 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.