Querying and expanding references in Sanity.io

23 replies
Last updated: Feb 13, 2023
For example... I have a doc type "experience" that references another type "Skill". I'm able to see my array of "skills" but when I map over them, the image is undefined
Could you show the query youre using?
sure.
export const experienceQuery = groq`
*[_type == "experience"]
`
This is the simple query, which returns all the experience docs.
Part of those results is this:
This is the type definition for both those document types
This is the result of
experience?.jobFunction?.technologies
I think the issue is the available fields on this don't include
image
, so I guess I'm not clear on how to get the image URL from this reference.
Yeh, you need to expand those references like technology->
If you are manually typing your data i would reccomend checking out groqd where you build your query by creating a validation schema which can then be inferred to ts
can you link me to that? I think I understand what you're saying. I'm not getting enough data with my original query
Also in general i prefer to be explicit with groq queries, noe you are basically ‘fetching everything’
Also highly reccomend this guide https://hdoro.dev/learn-groq
Thanks, I'll look this stuff over.
So it looks like I should be using something like this, which would get me all the experience docs and their data, as well as the expanded references for technologies.

*[_type == "experience"]{
  ...,
  technologies[]->,
}
Annd nope.
this is what I'm trying to expand
hahha, I got it
*[_type == "experience"]|order(dateStarted desc) {
  ...,
    jobFunction {
      technologies[]->
        }
}

Awesome!
I definitely see what you mean by being more targeted. That was my initial query, so now it makes sense more, after expanding those references within the fieldset
*[_type == "experience"]|order(dateStarted desc) {
  ...,
  employmentInformation {
    ...,
    professionalReference[]->
  },
  jobFunction {
    technologies[]->,
      points[]
  }
}
I don't know if this helps, but here's how I'm fetching the image URL and metadata:
"image": image{
  ...,
  ...asset->{
    "palette": metadata.palette,
    "lqip": metadata.lqip,
    url
  }
},

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?