Including referenced document's slug field in Sanity query results
Looking at your desired object structure, you want to have both the reference object itself AND a specific field (the slug) from the referenced document. This is a common pattern in Sanity when you need to maintain the reference relationship while also having quick access to certain fields.
You can achieve this using GROQ's reference access operator (->) combined with projection. Here's how:
*[_type == "yourDocumentType"] {
internalLinks[] {
_key,
_type,
item,
"slug": item->slug.current
}
}This keeps your item field as the reference object (with _ref and _type), while also dereferencing to grab the slug and projecting it as a separate field at the same level.
If your referenced document has a slug object (like slug.current), use the syntax above. If it's a direct string field, just use item->slug.
Alternative approach - if you want to be more explicit about the reference structure:
*[_type == "yourDocumentType"] {
internalLinks[] {
_key,
_type,
item {
_ref,
_type
},
"slug": item->slug.current
}
}The key here is using the -> operator to dereference and access fields from the referenced document, while keeping the original reference intact. The -> operator internally executes a subquery to fetch the referenced document's data, so you can pull out any field you need (slug, title, etc.) while maintaining the reference relationship.
This pattern is particularly useful when you need the reference for mutations/updates but also want to display data without additional queries on the frontend.
Show original thread59 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.