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

Querying mixed-fields arrays in GROQ for a complex schema.

4 replies
Last updated: Jun 20, 2023
I’m having some trouble constructing a GROQ query for an array that holds a mix of objects and references. This is not the actual schema (it’s way to large to paste here), but analogous to…
export const person = defineType({
  name: 'person',
  type: 'document',
  title: 'Person',
  fields: [
    defineField({
      name: 'name',
      type: 'string'
    }),
    defineField({
      name: 'contacts',
      type: 'array',
      of: [
        {
          name: 'phoneNumber',
          type: 'string',
        },
        {
          name: 'addresses',
          type: 'reference',
          to: [
            {type: 'address'}
          ]
        }
      ]
    })
  ]
})
I’m hung up on the query. This will pull up the addresses, but phoneNumbers are `null`…

*[_type == 'person'][0] {
  name,
  contacts[] -> {
    ...
  }
}
… and this will bring up the phoneNumbers but not the addresses…

*[_type == 'person'][0] {
  name,
  contacts[] {
    ...
  }
}
I’m stumped, any ideas?
Jun 20, 2023, 9:35 PM
When you’re querying a mixed-fields array, you could be explicit:

*[_type == 'person'][0] {
  name,
  contacts[] {
    phoneNumber,
    addresses->
  }
}
Or you could be more general:


*[_type == 'person'][0] {
  name,
  contacts[] {
    _type == 'reference' => @->,
    _type != 'reference' => @
  }
}

Jun 20, 2023, 9:38 PM
Interesting. Okay, I’ll give that a crack.
Jun 20, 2023, 9:38 PM
thank you
Jun 20, 2023, 9:38 PM
alright, got it now. The actual schema was heinously more complex than what I outlined above 🙂 thank you so much.
Jun 20, 2023, 9:50 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?