Search code examples
sanity

How do I limit the amount of document inside a schema in Sanity?


I have a Schema called Blog and I only want there to be one Blog object and want to limit it to only one Blog object.

For example, Blog has an "Article". I don't want there to be multiple "Article" and want to put a limit to one article in a blog.


Solution

  • Are you trying to create a reference from an object of type "blog" to another of type "article"?

    if so, this will do it:

    {
      name: 'blog',
      type: 'object',
      fields: [
        {
          title: 'Article',
          name: 'article',
          type: 'reference',
          to: [{type: 'article'}]
        }
      ]
    }
    

    This will allow an editor to select only one "article" to reference to.

    See the sanity docs for the reference field here: https://www.sanity.io/docs/reference-type


    If instead you're trying to create a "singleton" document inside of Sanity Studio, one that an editor can't create more of, then this will do it:

    // deskStructure.js
    import S from '@sanity/desk-tool/structure-builder'
    
    export default () =>
      S.list()
        .title('Base')
        .items([
          S.listItem()
            .title('Blog')
            .child(
              S.document()
                .schemaType('blog')
                .documentId('blog')
            ),
          ...S.documentTypeListItems().filter(listItem => !['blog'].includes(listItem.getId()))
        ])
    

    Reference the guide in the Sanity docs: https://www.sanity.io/docs/create-a-link-to-a-single-edit-page-in-your-main-document-type-list