Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

What is the recommended way to deal with something like role in GROQ which can return different things?

5 replies
Last updated: Feb 5, 2021

GROQ question, what is the recommended way to deal with something like

role
which can return different things?

Feb 5, 2021, 10:31 AM

Is it role[] -> _type role || someOtherDocType?

role[] -> {
  _type == 'role' => @{
    label
  }
  _type == 'other' => @{
    name
  }
}
The above could handle the different documents you reference.

Feb 5, 2021, 11:22 AM

Interesting let me try

Feb 5, 2021, 12:00 PM

I ended up with this, maybe there is something better 🤔

_type == "person" => {
   _id,
   name,
   role[]
  },
 _type == "institution" => {
   _id,
   name,
   role[]->{name}
}

Feb 5, 2021, 12:41 PM

I would maybe only use references and not strings for a more predictable editor, but if it works :-)

Feb 5, 2021, 2:12 PM

Good point! thanks

user G

Feb 5, 2021, 2:17 PM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.