GROQ Query - Can I Get Draft Version of a Document Referenced by the Parent Document?

3 replies
Last updated: Jul 28, 2022
Hello all. Need some help in knowing if this is practically allowed in GROQ query.Can I get the draft version of the document (if present, else published) referenced by the parent document with id
xxxx (and not
drafts.xxxx
). So if parent document is referencing
xxxx
, can I show the draft document drafts.xxxx if it exists even though the direct reference of the draft is not added in parent?I tried using match, coalesce but do not seem to get the expected result.

https://groq.dev/jonYis0Kvftcb7RPxZO62V
AI Update

This is definitely possible in GROQ! You're asking about the common scenario where a parent document references a published document ID (like xxxx), but you want to show the draft version (drafts.xxxx) if it exists, even though the parent only stores the published reference.

The key technique is to use GROQ's scoring and ordering to prioritize draft documents. Here's the pattern from Sanity's official recipe:

*[_type == 'pokemon' && slug.current == "bulbasaur"]
  | score(_id in path("drafts.**"))
  | order(_score desc)[0]

For your specific case with references, you'd adapt it like this:

*[_id == "parent-doc-id"][0]{
  title,
  "referencedDoc": *[_id in [
    "drafts." + ^.referencedField._ref,
    ^.referencedField._ref
  ]] | score(_id in path("drafts.**")) | order(_score desc)[0]
}

This works by:

  1. Creating an array with both the draft ID (drafts.xxxx) and published ID (xxxx)
  2. Using score(_id in path("drafts.**")) to assign a higher score to draft documents
  3. Using order(_score desc)[0] to select the highest-scored document (draft if it exists, otherwise published)

Alternative: Use the previewDrafts perspective

Instead of handling this in your query, you can use Sanity's perspectives feature. When you set perspective=previewDrafts in your API request, Sanity automatically prioritizes drafts over published documents when resolving references:

const query = '*[_id == "parent-doc-id"][0]{ ..., referencedField-> }'
const result = await client.fetch(query, {}, { perspective: 'previewDrafts' })

This is the recommended approach for preview/editing environments because it handles all references automatically without complex query logic. The previewDrafts perspective ensures that whenever a draft exists, it takes precedence over the published version - exactly what you're looking for.

For your GROQ playground link, the perspective approach won't work there, but the scoring pattern should solve your issue perfectly!

Something like this should work… interestingly it’s matching against docs with the same
_rev
attribute

*[_type == "user" && _id == "5766c34-8b0f-db36-67ef-7a0df57770c8"]
{
  ...,
  posts[]->{
    ...,
    "hasDraft": *[_type == "post" && _id in path("drafts.**")]
  }
}
Thanks
user J
for the response. Turns out I was able to get what I was looking for from below GROQ -
*[_type == "user"]
{
  ...,
  'posts': *[_type == 'post' && (_id in (^.posts[]._ref )|| _id in ^.posts[]{ '_ref': 'drafts.'+_ref }._ref )]
}
This gives both versions (draft & published) of the referenced document which can be fed into a system which can determine which version to pick. Thanks for the lead.🤘 Regarding the
_rev
, I think that was my bad in preparing the mock scenario data.

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?