0

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

ytrewq
  • 59
  • 1
  • 10

1 Answers1

0

You don't necessarily need to add this count in the schema. Some issues I see with it being in schema include:

  1. You delete an article - should others' index reflect that? For example, should article #11 become #10 if the 10th is deleted?
  2. An article is created but never published - should it have a reserved index even though other newer ones were already published?
  3. 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

Henrique Doro
  • 436
  • 4
  • 7
  • Sorry I'm didn't get back sooner, I was taking a few days off. Thank you for a thorough explanation, it works perfectly! One more question though, would it be possible to do it in the reverse order as well (the newest post has an index of 1, the next one – 2, and so forth) – ytrewq Jul 08 '21 at 16:08
  • 1
    Never feel pressured to answer in time - we need more calm and I'm glad you took days off :) You sure can! All you have to do in the example above is to change the comparison between article dates: `_createdAt < ^._createdAt` (instead of `>`). This will count all articles newer than the current one, which would be 0 for the newest article, hence index of 1 – Henrique Doro Jul 08 '21 at 16:53
  • Awesome! Thank you so much :) – ytrewq Jul 08 '21 at 19:25