๐Ÿ”ฎ Sanity Create is here. Writing is reinvented. Try now, no developer setup

Trouble with GROQ and querying a specific field in a schema.

6 replies
Last updated: May 10, 2020
Hey all ๐Ÿ‘‹ ,

Having a bit of trouble with GROQ. Normally I use GraphQL with Gatsby but trying to avoid installing a graphql client in a non-gatsby project I'm working in but I can't seem to figure out how to grok it (pun intended).
I have a basic schema that looks like this:


export default {
  name: "landingPage",
  title: "/landing",
  type: "document",
  fields: [
    {
      name: "hero",
      title: "Landing Page Hero",
      type: "landingHero",
      options: { collapsible: true },
    },
  ],
  preview: {
    select: {
      title: "hero",
      subtitle: "heading",
    },
    prepare(selection) {
      const { subtitle } = selection
      return {
        title: "Hero Section",
        subtitle: subtitle,
      }
    },
  },
}

I've tried:

*[_type=="landingPage"] {
	_id,
  landingHero->
}

*[_type=="landingPage"] {
	_id,
  landingHero->{heading}
}

*[_type=="landingPage"] {
	_id,
  hero->
}
May 9, 2020, 11:38 PM
What is the schema definition for the
landingHero
type?
May 10, 2020, 1:57 AM
Given the
collapsible
option I would assume that it's an object that somewhere within it holds a reference, maybe? Or maybe it's not a reference in the first place?

*[_type == "landingPage"][] {
  _id,
  hero
}
Should give you the content of that field. If the content of hero is
{_ref: 'someDocId'}
, then the last query you tried should be correct.
I suspect however that it's either just an inline object (in which case just doing the query I mentioned above should give you everything within the
hero
field), or there is a nested reference field within it, like:
{
  _id: 'someId',
  hero: {
    _type: 'landingHero',
    target: {
      _ref: 'someDocumentId'
    }
  }
}
In which case the query would be

*[_type == "landingPage"][] {
  _id,
  hero {
    target->
  }
}
If there are other non-reference fields within the
landingHero
, you can add
...
to fetch "all fields", then expand any references, like:

*[_type == "landingPage"][] {
  _id,
  hero {
    ...,
    target->
  }
}
May 10, 2020, 2:02 AM
That was very helpful
user Z
May 10, 2020, 3:02 AM
it wasn't a reference correct
May 10, 2020, 3:02 AM
it works thanks to your examples, thank you very much
May 10, 2020, 3:02 AM
and good to know about the '...'
May 10, 2020, 3:02 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?