Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Schema Specification for a Document - Is There a Way to Specify That Field To Be Unique?

6 replies
Last updated: Jul 13, 2020
In schema specification for a document, is there a way to specify that I want a field to be unique? That no two documents with the same content in that field can exist? I find myself cleaning up duplicates quite a lot...
Jul 10, 2020, 7:44 PM
If this is an array field for example, you could add the
unique()
function to the validation. This requires all values within the array to be unique by doing a deep comparison.

{
  title: 'Category Set',
  name: 'categorySet',
  type: 'array',
  of: [{type: 'string'}],
  validation: Rule => Rule.unique()
}
Jul 10, 2020, 8:08 PM
Hmm... Can the validation rule be put on other types as well, or does it have to be an array?
Given this:

  type: 'document',
  title: 'Language texts',
  name: 'i18n',
  fields: [
    {
      name: 'key',
      title: 'Identifier',
      type: 'string',
    },
    {
      name: 'value',
      title: 'Translations',
      type: 'localeString',
    },
  ]
I want the
key
field to be unique.
Jul 10, 2020, 8:11 PM
Yes it can be applied to the
key
field. Thank you very much! πŸ™‚
Jul 10, 2020, 8:18 PM
Indeed! Thanks for posting back πŸ™‚
Jul 10, 2020, 8:37 PM
Well I was a bit quick on reporting success with the validation rule here. The
unique
rule is not valid on document descriptors. I wish it was.
That leaves me with trying to create a custom rule which queries for document keys on input. Anybody have a clue as to how I can query existing objects inside a custom rule?
Jul 13, 2020, 5:42 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?