How to dereference array of testimonial references in GROQ query?
-------
Hi everyone, just started using Sanity a few days ago and am having trouble writing a join query for my reference type. End goal is to create a testimonials slider on my homepage.
Schema.js:
export default {
name: 'homepage',
type: 'document',
title: 'Homepage Data',
fields: [
...
{
name: 'home_testimonials',
type: 'array',
of: [{ type: 'reference', to: [{ type: 'testimonial' }] }],
title: 'Homepage Testimonials',
},
],
}; // testimonial.js
export default {
name: 'testimonial',
title: 'Testimonial',
type: 'document',
fields: [
{
name: 'author',
type: 'string',
title: 'Author',
},
{
name: 'jobTitle',
type: 'string',
title: 'Job Title',
},
{
name: 'content',
type: 'string',
title: 'Content',
},
],
};https://www.sanity.io/docs/reference-type ) I wrote this GROQ query:
export const homepageQuery = `*[_type == "homepage"] {
...,
"home_testimonials": testimonial[]{
testimonial->{content, jobTitle, author}
}
}`;home_testimonials: [{
"_key":"4185e4bd9cea",
"_ref":"07c6f4c5-f09b-456b-9d1b-95af390f389b",
"_type":"reference"
},
...
] home_testimonialsfilled with all my custom fields (
jobTitle,
author, etc...) instead of just the reference ID.
Pretty sure I'm approaching this all wrong so any pointers are appreciated.
🙏
Glad you figured it out! For anyone else who comes across this thread with a similar issue, the solution is to fix the GROQ query syntax. The correct query should be:
*[_type == "homepage"] {
...,
"home_testimonials": home_testimonials[]->{
content,
jobTitle,
author
}
}The key differences:
- Use
home_testimonials[]->(the actual field name from your schema, not "testimonial") - The
->operator dereferences the reference to get the actual testimonial document - No need for a nested
testimonial->inside
This will expand each reference in the home_testimonials array and return the actual content, jobTitle, and author fields from each referenced testimonial document.
You can learn more about dereferencing in GROQ in the reference type documentation and the GROQ query cheat sheet.
Show original thread1 reply
Was this answer helpful?
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.