👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Querying for a document based on its `_ref` number in Sanity.io.

3 replies
Last updated: Sep 13, 2023
is it possible to query for a document based on its
_ref
number?
Sep 13, 2023, 12:09 PM
The
_ref
value is equivalent to the document’s non-draft
_id
and gets ascribed to a reference, so in all cases I can think of, the answer would be yes. There’s an idiomatic approach to filtering in a subquery that uses that
_ref
value:

*[_type == 'author']{
  ...,
  'posts': *[_type == 'post' && author._ref == ^._id]
}
Here, the query for
posts
wants all posts where the author that’s referenced (from within the post document) equals the author
_id
from the top-level scope.
Sep 13, 2023, 1:28 PM
What you can’t really do is expect to use
_ref
at the top-level scope. E.g.,

*[_type == 'post' && _ref == $ref][0]
However, that’s because you’d use
_id
instead of
_ref
.
Sep 13, 2023, 1:29 PM
thanks... i went with
*[_type == 'map' && _id == '${mapID}']
Sep 13, 2023, 2:52 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?