How to prevent self-reference in parent-child category relationships?

4 repliesLast updated: Nov 29, 2025

Hi everyone, I'm new to Sanity trying to setup a child parent reference (category / subcategory) but how do I prevent a self reference?
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:

Important notes:

This pattern works for any self-referential scenario where you need to prevent a document from referencing itself!

Show original thread
4 replies

Was this answer helpful?

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.

Related contributions