Unlock seamless workflows and faster delivery with our latest releases – get the details

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 remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?