Query posts by category reference in Sanity schema
Based on your schema, you have posts with an array of category references. The key to querying posts filtered by category is understanding how to work with reference arrays in GROQ.
Here's how to query posts by category:
Filter posts that have a specific category:
*[_type == "post" && references("category-id-here")] {
title,
categories[]->
}The references() function checks if any reference in your categories array points to the specified category ID.
Get the full category details:
To dereference the categories array and get the actual category data (not just the references), use the -> operator:
*[_type == "post"] {
title,
categories[]->{
title,
description
}
}The categories[]-> syntax means "for each item in the categories array, dereference it and return the full document."
Filter by category title/slug:
If you want to filter by a category's title instead of its ID:
*[_type == "post" && "Technology" in categories[]->title] {
title,
categories[]->
}Common mistake to avoid:
Don't try categories-> without the [] - that won't work because categories is an array, not a single reference. The [] tells GROQ to iterate through the array items.
The reference access operator (->) performs a subquery internally to fetch the referenced document. When you use categories[]->, it resolves each reference in the array and replaces it with the actual category document data.
If you're still having issues, the problem is likely in how you're structuring the query - make sure you're using categories[]-> (with the brackets) rather than categories-> when working with your array of references.
Show original thread25 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.