
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeGreat 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:
filter option takes a function that receives the current document as context_id matches the current document's IDdocument._id.replace(/^drafts\./, '') to handle both draft and published versions!(_id in path("drafts.**")) part ensures we're comparing against the published IDImportant notes:
document properties exist before using them (the example above assumes _id is always present, which it should be)This pattern works for any self-referential scenario where you need to prevent a document from referencing itself!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store