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

Help needed with expanding nested references in a Sanity query

3 replies
Last updated: Jul 20, 2021
Maybe I'm losing my mind, or don't have enough caffeine in my system, but I can't work out how to expand a nested reference, but also keep its sibling. I have a
submenuItems
array that can contain URL or a reference to another document. However, I can't seem to expand any references it encounters without losing the sibling submenuItem that happens to be a normal url/link.
Jul 20, 2021, 3:55 PM
Sample, full query result:
[
  {
    "_createdAt": "2021-07-20T15:28:00Z",
    "_id": "2bf5b5af-c3cd-4ad9-a57f-f4bb8ef3841d",
    "_rev": "UubfLilb6M2LgUxBYJcHmh",
    "_type": "navigation",
    "_updatedAt": "2021-07-20T15:28:56Z",
    "id": "kevin-navigation",
    "links": [
      {
        "_key": "3b1e45d65ac8",
        "_type": "linkItem",
        "href": "<https://google.com>",
        "name": "Top Link",
        "tabBehaviour": true
      },
      {
        "_key": "6c5ebebb321f",
        "_type": "linkItem",
        "href": "<https://rte.ie/>",
        "name": "Second Link",
        "submenuItems": [
          {
            "_key": "51e483ed1dbf",
            "_ref": "f342b02b-99c0-470a-b857-8898de156cab",
            "_type": "reference"
          },
          {
            "_key": "8cb9dc272c3e",
            "_type": "linkItem",
            "href": "<https://nufc.co.uk>",
            "name": "Newcastle United"
          },
          {
            "_key": "fa6f1280f477",
            "_ref": "55d400bf-8ea5-4e6b-9232-d3a2b4e2c267",
            "_type": "reference"
          }
        ]
      },
      {
        "_key": "53e111fad541",
        "_type": "linkItem",
        "href": "<https://lol.com>",
        "name": "Tertiary Link"
      }
    ],
    "title": "Kevin Navigation"
  }
]
Jul 20, 2021, 3:56 PM
*[_type == "navigation" && id == "kevin-navigation"]{
  links[]{ 
    name, 
    href, 
    submenuItems[]->{ 
      ...
    }
  }
}
This expands the references entirely, but loses the sibling items of a different
_type
whilst if I remove the
->
it returns the opposite. Something to do with the projection, and mapping over I think, but can't work it out ๐Ÿ˜‚ Any help mucho appreciado.
Jul 20, 2021, 4:00 PM
I think I may sussed it, thanks for Anders code snippet. Just in case anyone is stuck in a rut and questioning their career-choice for a few hours ๐Ÿ˜„
Jul 20, 2021, 4: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?