1

In Sanity, for a given document type named message, how can I get the _id of the newest message document?

dotnetCarpenter
  • 10,019
  • 6
  • 32
  • 54
ArneHugo
  • 6,051
  • 1
  • 26
  • 47

1 Answers1

2

Query

You can actually do that in a single query in GROQ (Sanity's query language):

*[_type == 'message'] | order(_createdAt desc) [0] ._id

Query Explanation

This query has five parts.

  1. *[_type == 'message']: select all documents of type 'message'.
  2. |: pipe the messages (so we can perform the rest of the operations)
  3. order(_createdAt desc): order the messages from newest to oldest (_createdAt is set automatically by Sanity when a document is created)
  4. [0]: select the first message from the list (which is also the newest)
  5. ._id: select the _id of the newest message

To fetch another property, multiple properties or the entire message object, replace the last part of the query.

ArneHugo
  • 6,051
  • 1
  • 26
  • 47
  • 1
    you're allowed to check off your own answer as the correct one. Makes it easier for others to identify a good solution. – thomax Apr 23 '19 at 14:28