How to prevent self-reference in child-parent setup in Sanity using custom validation or filter option.
4 replies
Last updated: Sep 7, 2023
AI Update
Great question! Preventing self-references in parent/child relationships is a common need. The good news is you can use the filter option on your reference field to exclude the current document.
Here's how to prevent a category from referencing itself as a subcategory:
{
name: 'category',
type: 'document',
fields: [
{
name: 'title',
type: 'string'
},
{
name: 'parentCategory',
type: 'reference',
to: [{type: 'category'}],
options: {
filter: ({document}) => {
return {
filter: '_id != $id && !(_id in path("drafts.**"))',
params: {
id: document._id.replace(/^drafts\./, '')
}
}
}
}
}
]
}What's happening here:
- The
filteroption takes a function that receives the currentdocumentas context - We return a GROQ filter that excludes documents where
_idmatches the current document's ID - We use
document._id.replace(/^drafts\./, '')to handle both draft and published versions - The
!(_id in path("drafts.**"))part ensures we're comparing against the published ID
Important notes:
- Always check that
documentproperties exist before using them (the example above assumes_idis always present, which it should be) - This filter only constrains the search results when selecting a reference—it doesn't validate existing references if you change the logic later
- The filter uses the published document ID for comparison, which is what you want for referential integrity
This pattern works for any self-referential scenario where you need to prevent a document from referencing itself!
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.