Querying for displayed document in GROQ

6 replies
Last updated: Aug 20, 2020
Hi! one quick question:With GROQ, how can I write a query that fetches the "displayed" document? By "displayed" I mean either the draft (if there's one) or the published document (if there's no draft).
Aug 13, 2020, 7:49 AM
Morning! This might depend on your main query, but how about something like this?
*[_type == "post" && slug.current == "my-post"][0]{
  ...*[_id in [^._id, "drafts." + ^._id]] | order(_updatedAt desc)[0],
}
Aug 13, 2020, 8:18 AM
Morning! This might depend on your main query, but how about something like this?
*[_type == "post" && slug.current == "my-post"][0]{
  ...*[_id in [^._id, "drafts." + ^._id]] | order(_updatedAt desc)[0],
}
Aug 13, 2020, 8:18 AM
oh nice! Actually I already know the id of the document, so I guess I can simplify the query.
Aug 13, 2020, 8:56 AM
*[_id in [$id, "drafts." + $id]]
✌️
Aug 13, 2020, 9:08 AM
Awesome!
Aug 13, 2020, 9:08 AM
PS: just realized now why you added "order(_updatedAt desc)[0]". Because otherwise we might get the published document instead of the draft.
Aug 20, 2020, 4:28 PM

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?