Query multiple document types with conditional projections returning null
Looking at your query, you're very close! The syntax you're trying to use is correct - conditional projections with the _type == 'value' => pattern is indeed the right approach for querying arrays with multiple document types.
Based on the example from the Query Cheat Sheet, here's the correct syntax:
*[_type == "resourcesPage"][0] {
mainHeading,
subHeading,
bodyText,
resourceItems[]-> {
_type == "youTube" => {
_type,
title,
url,
description,
thumbnail
},
_type == "blogPost" => {
_type,
title,
summary,
mainImage,
author->{ name, avatar },
"tags": tags[]-> tagName,
"slug": slug.current
}
}
}The key points about conditional projections:
- Use the arrow operator (
->) to follow the references first:resourceItems[]-> - Then add conditional projections inside the projection block using
_type == 'value' => { fields } - Each condition returns only the specified fields for that document type
- This preserves the original array order (no need for sorting plugins!)
- No null values are returned for missing fields
This approach is much cleaner than:
- Separating into multiple arrays and concatenating on the frontend
- Including all fields and getting nulls for non-existent fields
- Using ordering plugins to maintain sequence
The conditional projection syntax gives you exactly what you need: an array of mixed document types, each with their own specific fields, in the original order. This is part of GROQ's projection features that allow you to transform and reshape data based on conditions.
If you're getting null as a result, double-check that:
- Your
resourceItemsarray actually contains references (has_refvalues) - The referenced documents exist and have the
_typevalues you're checking for - You're using the dereference operator
->correctly
You can test this step-by-step in Vision by first querying just resourceItems[]-> to see what the dereferenced documents look like, then adding the conditional projections.
Show original thread11 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.