Resolve reference in Block Content in Sanity.io

1.9k views Asked by At

I have the Content Block in Sanity like so:

export default {
title: "Block Content",
name: "blockContent",
type: "array",
of: [
    /// stuff here
    {
        title: "Book",
        type: "reference",
        to: [{ type: "book" }],
    },
],
};

When making a query like

'*[_type == "post"]{...,body[]{..., asset->{..., "_key": _id}, markDefs[]{..., _type == "internaLink" => {"slug": @.reference->slug}}}';

I get the reference, but I want to return the full Document. I tried every method but the documentation only explain references outside Content Blocks and those methods aren't working.

This is what's returned from the Query:

  _createdAt: '2020-12-07T14:43:34Z',
  _id: '9d628aa6-aba7-4b53-aa9f-c6e97583baf9',
  _rev: 'ZZ0GkIKCRvD0tdMQPywPfl',
  _type: 'post',
  _updatedAt: '2020-12-07T14:43:34Z',
  body: [
    {
      _key: '4184df372bae',
      _type: 'block',
      children: [Array],
      markDefs: [],
      style: 'normal'
    },
    {
      _key: '56bed8835a7d',
      _ref: 'dc2eefee-2200-43e1-99c7-ea989dda16ba',
      _type: 'reference'
    }
  ],
  title: 'Example'
2

There are 2 answers

0
IActuallyDontKnow On BEST ANSWER

Solved, I'm writing the solution here as I found nothing on the web. Basically I tried anything randomly until I got the desired result. The query is:

_type=="reference"=>^->
0
Hunter Copp On

I had a similar situation where I had was grabbing a story object that had a body which was a blockContent, and I had just added a blog reference as a block option to the body.

I solved it by using this query:

const query = groq`*[_type == "story" && slug.current == $slug][0]{
  title,
  description,
  body[]{
      _type == 'blog' => @->,
      _type != 'blog' => @,
  }
}`

It loops through all the array items inside of the body and if a specific one is a blog, then it dereferences it by using ->, otherwise it outputs the already existing value.