Querying references in Sanity: how to search posts by category
15 replies
Last updated: Jun 21, 2021
D
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:
Question is how can I query all posts based on a dynamically provided category?
Any help will greatly appreciated. Thanks
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
D
Groq?
Jun 20, 2021, 4:16 PM
D
exactly
Jun 20, 2021, 4:17 PM
Jun 20, 2021, 4:18 PM
D
Thanks, Christopher, I will try that.
Jun 20, 2021, 5:25 PM
D
Hi Christopher I tried that and I got :• No documents found in dataset
productionthat match query:
Jun 21, 2021, 7:44 AM
D
Here is the query i use:
*[_type == "post" && (categories[]->tiltle match "nodejs")]
Jun 21, 2021, 7:44 AM
D
When I try :
*[_type == "category"]{
title
}
Jun 21, 2021, 7:46 AM
D
here is what i get:
"result":*[*_2 items_
0:*{*_1 item_
"title":"reactjs"
}
1:*{*_1 item_
"title":"nodejs"
}
]
Jun 21, 2021, 7:46 AM
D
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
D
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
D
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.