Simplify GROQ query with optional fields
May 21, 2023
In working with Sanity and GROQ, there might be instances where you need to filter data using an optional field, and want a default value to kick in when null values are returned. For instance, consider an __i18n
field added after a significant amount of content was already created. In this scenario, there's a batch of content that lacks a set value. In such a case, we'd prefer to use "en"
as the fallback.
1*[type=="article" && (__i18n_lang == $locale || ($locale == "en" && __i18n_lang == null) )] { ... }
This requirement can be elegantly addressed using the coalesce
function directly within the filter. By doing so, we can default the __i18n
field to "en" using a more straightforward and compact syntax: coalesce(__i18n, "en")
. This function greatly simplifies the query, making your code cleaner and more efficient.
1*[type=="article" && coalesce(__i18n, "en")] { ... }