Expanding nested reference in GROQ query for array within flexible content
Looking at your GROQ query, the structure appears correct for expanding nested references. The issue you're experiencing is likely due to how the workGallery object is structured in your schema. Let me help you troubleshoot this.
Your query structure looks good:
*[_type== "home"] {
pageSections[] {
...,
testimonial->,
works[] {
...,
work->
},
}
}The reference access operator (->) should work for nested arrays just like it does for your testimonial reference. Here are the most common reasons why it might not be working:
1. The work field might not be a reference type
Check your schema definition for the workGallery object. The work field inside the works array needs to be defined as a reference type:
{
name: 'works',
type: 'array',
of: [{
type: 'object',
fields: [{
name: 'work',
type: 'reference', // Must be type 'reference'
to: [{type: 'work'}]
}]
}]
}2. Try using conditional expansion
Sometimes when dealing with flexible content or union types in arrays, you need to be more explicit. Try this variation:
*[_type== "home"] {
pageSections[] {
...,
_type == "singleTestimonial" => {
testimonial->
},
_type == "workGallery" => {
works[] {
...,
work->
}
}
}
}3. Check if the references are actually populated
Add a filter to see if the work references exist:
*[_type== "home"] {
pageSections[] {
...,
works[defined(work)] {
...,
work->
}
}
}4. Inspect the raw data structure
Try querying without the dereference first to see what the actual structure looks like:
*[_type== "home"] {
pageSections[] {
_type,
works[] {
work
}
}
}This will show you if work contains a _ref field (which means it's a proper reference) or if it's structured differently.
The most likely culprit is that the work field isn't defined as a reference type in your schema, or there's a mismatch between your schema definition and the actual document structure. Check your schema first, and if that looks correct, use the debugging queries above to see what the actual data structure looks like.
Show original thread4 replies
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.