I've created a Schema Type as below and I'd like to program it so that for each blog post it increments: 1 - first post, 2 - second post, and so forth (then this number will be used on multiple pages). A simple thing, but I couldn't find any information on how to do it. Would it be possible? Any links/examples/references would be appreciated.
// schemas/post.js
{
name: 'index',
title: 'Index',
type: 'number',
},
Thank you
You don't necessarily need to add this count in the schema. Some issues I see with it being in schema include:
#11
become #10
if the 10th is deleted?unique
feature to fields other than the _ids
themselves, so this could be very problematic.An alternative approach would be getting this value dynamically through GROQ, which (I think) is more resilient and easier to change in the future.
Here's an example query:
*[slug == $articleSlug]{
...,
// Count every older article and add 1 - that's the current article's index
"articleIndex": count(*[
// From every published article (non-draft)
_type == 'article' &&
!(_id in path("drafts.**")) &&
// Get only those older than the current one
_createdAt > ^._createdAt
]) + 1
}
If you find your queries getting complex and hard to manage, I'd suggest abstracting its parts as variables as I outline in my GROQ guide on writing complex queries 😉
Hope this helps 🙏