Help with filtering products by brand in a Sanity.io structure
Looking at your code, the structure itself is actually valid! Your filter syntax $brandId in brands[]._ref is correct GROQ, and the way you're chaining .child() should work. However, there are a few common issues that could prevent it from displaying products:
Most likely culprit: Schema field mismatch
Double-check your product schema. Your filter assumes brands is an array of references, like this:
{
name: 'brands',
type: 'array',
of: [{type: 'reference', to: [{type: 'brand'}]}]
}If your schema is actually different, you'll need to adjust:
If it's a single reference (not an array): Change your filter to:
.filter('_type == "product" && brands._ref == $brandId')If the field has a different name (like
brandsingular orbrandRef): Update your filter to match that field name
Alternative filter approach
You could also try using the references() function, which checks all reference fields automatically:
.filter('_type == "product" && references($brandId)')This is more forgiving and doesn't require you to specify the exact field path.
Other things to verify:
- Do you have data? Make sure you have products with brand references actually set
- Check for typos in field names between your schema and filter
- Try a simpler filter first to isolate the issue:If this shows products, then you know the issue is specifically with the brand filtering logic
.filter('_type == "product"')
About .schemaType()
You might see suggestions to add .schemaType('product') - while this can be helpful for tooling and autocomplete, it's not strictly required for the filter to work. It won't fix a filtering issue, but it doesn't hurt to include it:
S.documentList()
.schemaType('product') // optional
.title('Products')
.filter('_type == "product" && $brandId in brands[]._ref')
.params({ brandId })The most common issue here is that the filter doesn't match your actual schema structure, so start by verifying your brands field configuration!
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.