👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Querying references in Sanity: how to search posts by category

15 replies
Last updated: Jun 21, 2021
Hi everyone,I'm quite new to sanity and I'm learning through a series of tutorial but I've still some trouble with querying references.
Say i have post document like this:

fields: [
    
{
      
name: 'title',
      
title: 'Title',
      
type: 'string',
    
},
   
{
      
name: 'categories',
      
title: 'Categories',
      
type: 'array',
      
of: [{type: 'reference', to: {type: 'category'}}],
    
},
    
},
   and a category document like this:

fields: [
    
{
      
name: 'title',
      
title: 'Title',
      
type: 'string',
    
}

]

Question is how can I query all posts based on a dynamically provided category?
Any help will greatly appreciated. Thanks
Jun 20, 2021, 1:14 PM
By "query", do you mean GROQ, GraphQL, or other?
Jun 20, 2021, 3:30 PM
Groq?
Jun 20, 2021, 4:16 PM
So do you want to pull all posts that reference a certain category?
Jun 20, 2021, 4:16 PM
exactly
Jun 20, 2021, 4:17 PM
(categories[]->title match ["...."])
Jun 20, 2021, 4:20 PM
Thanks, Christopher, I will try that.
Jun 20, 2021, 5:25 PM
Hi Christopher I tried that and I got :• No documents found in dataset 
production
 that match query:
Jun 21, 2021, 7:44 AM
Here is the query i use:
*[_type == "post" && (categories[]->tiltle match "nodejs")]
Jun 21, 2021, 7:44 AM
When I try :
*[_type == "category"]{

title

}
Jun 21, 2021, 7:46 AM
here is what i get:
"result":*[*_2 items_

0:*{*_1 item_

"title":"reactjs"

}

1:*{*_1 item_

"title":"nodejs"

}

]
Jun 21, 2021, 7:46 AM
and when I do try this:
*[_type == "post" ]{

title,


categories[]->{title}

}
I get this:


"result":*[*_2 items_

0:  *{*  _2 items_

"categories":*[*_1 item_

0:*{*_1 item_

"title":"nodejs"

}

]


"title":"Another one"

}

1:*{* _2 items_

"categories":*[*_1 item_

0:*{*_1 item_

"title":"reactjs"

}

]

"title":"The first of many to come"

}

]
Jun 21, 2021, 7:51 AM
Sorry if the information is quite much. I'm just hoping i give you ab better insight as what i'm struggling with
Jun 21, 2021, 7:52 AM
Basically, i will like a use to search post by category. That is all
Jun 21, 2021, 7:52 AM
Hey Donald! This section on filters in the documentation could be helpful. Depending on how you have your document set up, it would look something like this:
*[_type == 'post' && category == 'your-category']
Jun 21, 2021, 4:26 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?