GROQ defined() filter not working despite non-empty field
I can see what's happening here! The defined(field) => field syntax is GROQ's conditional projection pair syntax, and it's likely disappearing because of how the => operator works with boolean conditions.
The => operator in GROQ projections is a conditional pair that only includes the field when the left side evaluates to true. The issue is that defined(field) returns a boolean, not the actual field value, so when you write defined(field) => field, you're saying "if defined(field) is true, include field", but the syntax might not be working as expected in your context.
Here's what's probably happening and how to fix it:
The Problem:
{
defined(myField) => myField // This might not work as expected
}Better Solutions:
- Simple conditional with default value using select():
{
"myField": select(
defined(myField) => myField,
"default value"
)
}- Direct field reference (fields are automatically omitted if undefined):
{
myField // Will be included if it exists
}- Using coalesce for fallback:
{
"myField": coalesce(myField, "fallback")
}- Conditional projection with proper syntax:
{
defined(myField) => {
"myField": myField
}
}The key issue is that the => operator in projections works as a conditional pair where the left side is evaluated as a boolean condition. When you use defined(field) => field, GROQ evaluates defined(field) (which returns true/false), and if true, it should include field. However, this syntax can be tricky and doesn't always behave as expected, especially if the field reference on the right side isn't in the correct scope.
Looking at the GROQ query cheat sheet, you can see examples of conditional projections like:
*[_type=='movie']{
...,
releaseDate >= '2018-06-01' => {
"screenings": *[_type == 'screening' && movie._ref == ^._id]
}
}The select() function from the GROQ conditionals documentation is usually more reliable for conditional field inclusion.
Debug tip: Console log the entire query result first without the projection to verify your field actually exists in the source documents, then gradually add your projection logic. The select() function is usually the most reliable approach for conditional field inclusion.
Show original thread6 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.