🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to reference a schema from a schema in Sanity.io

2 replies
Last updated: Feb 3, 2024
Does anyone know how you reference a schema from a schema? (i.e. self-referencing).
If a section can have children and one type of child can again be a [nested] section, how do you do that in the schema without creating a circular reference? Is this the right way?


export default defineType({
  name: "section",
  title: "Section",
  type: "object",
  fields: [

    defineField({
      type: "array",
      name: "blocks",
      title: "Content",
      of: [

        defineArrayMember(codeBlock), // <-- You can't do this with section because of circular reference
        
        defineArrayMember({ // <-- SO is this what you're supposed to do?
          name: "section",
          title: "Section",
          type: "section",
        }),

      ],
    }),

  ],

});
Feb 3, 2024, 5:16 PM
This works :
export default defineConfig({
  // ...other config
  schema: {
    types: [
      defineType({
        name: 'codeBlock',
        type: 'object',
        fields: [
          defineField({
            name: 'language',
            type: 'string',
          }),
          defineField({
            name: 'code',
            type: 'text',
          }),
        ],
      }),
      defineType({
        name: 'blocks',
        type: 'array',
        of: [
          defineArrayMember({
            type: 'section',
          }),
          defineArrayMember({
            type: 'codeBlock',
          }),
        ],
      }),
      defineType({
        name: 'section',
        type: 'object',
        fields: [
          defineField({
            name: 'blocks',
            type: 'blocks',
          }),
        ],
      }),
      defineType({
        name: 'post',
        type: 'document',
        title: 'Post',
        fields: [
          defineField({
            name: 'title',
            type: 'string',
          }),
          defineField({
            name: 'content',
            type: 'blocks',
          }),
        ],
      }),
    ],
  },
})
Some things to consider though:
• You can’t have “arrays-in-array”, so you’ll have to wrap them in an object to nest
• You can’t mix object types with primitive type in an array (e.g.
type: 'reference'
and a
type: string'
)• Nested structures, and especially “infinite” nested structures can be a bit of an anti-pattern:
◦ It’s easy to blow up the
unique attribute count ◦ It can be a bit unruly to query
Feb 3, 2024, 5:37 PM
Thanks
user Y
!
Feb 3, 2024, 5:39 PM

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?