You don't necessarily need to add this count in the schema. Some issues I see with it being in schema include:
- You delete an article - should others' index reflect that? For example, should article
#11
become #10
if the 10th is deleted?
- An article is created but never published - should it have a reserved index even though other newer ones were already published?
- What happens if accidentally numbers coincide and indexes are shared? Sanity currently doesn't have a
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