Querying an array with multiple document types in Sanity.io
Good question! When you have an array with references to different document types, you need to use conditional projections in GROQ to handle each type differently.
The key is using the _type field to conditionally project different fields based on the document type. Here's how you'd modify your query:
*[_type == "resourcesPage"][0] {
resourceItems[]-> {
_type == "youTube" => {
_id,
_type,
title,
description,
url,
thumbnail
},
_type == "blogPost" => {
_id,
_type,
title,
subtitle,
slug,
publishedDate,
mainImage {
altText,
asset->
},
author->,
tags[]->
}
}
}The syntax _type == "youTube" => { ... } is a conditional projection that only applies when the condition is true. You can chain multiple conditions for each document type in your array.
If you want to include some common fields for all types plus type-specific fields, you can combine this with the ellipsis operator (...):
*[_type == "resourcesPage"][0] {
resourceItems[]-> {
...,
_type == "youTube" => {
"videoUrl": url,
"videoThumbnail": thumbnail
},
_type == "blogPost" => {
"postSlug": slug.current,
"postImage": mainImage.asset->url,
author->
}
}
}The ... includes all fields from the referenced document, and then the conditional projections add or override specific fields based on the type. Note that the ellipsis is always evaluated first regardless of position, so any fields you define after will override the original values if they have the same name.
This pattern works great for heterogeneous arrays and gives you full control over what data you fetch for each document type!
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.