Querying and expanding references in Sanity.io
23 replies
Last updated: Feb 13, 2023
K
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
Feb 12, 2023, 12:50 PM
S
Could you show the query youre using?
Feb 12, 2023, 1:26 PM
K
sure.
Feb 12, 2023, 1:29 PM
K
export const experienceQuery = groq` *[_type == "experience"] `
Feb 12, 2023, 1:30 PM
K
This is the simple query, which returns all the experience docs.
Feb 12, 2023, 1:30 PM
K
Part of those results is this:
Feb 12, 2023, 1:30 PM
K
This is the type definition for both those document types
Feb 12, 2023, 1:32 PM
K
This is the result of
experience?.jobFunction?.technologiesI 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.
Feb 12, 2023, 1:39 PM
S
Yeh, you need to expand those references like technology->
Feb 12, 2023, 1:46 PM
S
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
Feb 12, 2023, 1:47 PM
K
can you link me to that? I think I understand what you're saying. I'm not getting enough data with my original query
Feb 12, 2023, 1:48 PM
S
Feb 12, 2023, 1:51 PM
S
Also in general i prefer to be explicit with groq queries, noe you are basically ‘fetching everything’
Feb 12, 2023, 1:51 PM
S
Also highly reccomend this guide https://hdoro.dev/learn-groq
Feb 12, 2023, 1:52 PM
K
Thanks, I'll look this stuff over.
Feb 12, 2023, 2:02 PM
K
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[]->, }
Feb 12, 2023, 2:30 PM
K
Annd nope.
Feb 12, 2023, 2:43 PM
K
this is what I'm trying to expand
Feb 12, 2023, 2:43 PM
K
hahha, I got it
Feb 12, 2023, 2:58 PM
K
*[_type == "experience"]|order(dateStarted desc) { ..., jobFunction { technologies[]-> } }
Feb 12, 2023, 2:58 PM
S
Awesome!
Feb 12, 2023, 3:30 PM
K
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
Feb 12, 2023, 3:33 PM
K
*[_type == "experience"]|order(dateStarted desc) { ..., employmentInformation { ..., professionalReference[]-> }, jobFunction { technologies[]->, points[] } }
Feb 12, 2023, 3:33 PM
M
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 } },
Feb 13, 2023, 3:48 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.