How to access the actual value of a reference in a document in Sanity.io.

2 replies
Last updated: May 15, 2024
One of my documents is just showing a reference instead of the actual reference value. how can I get the actual value?

origin: 
  _ref: "1ec9e722-3636-490d-9094-e102a4fca275"
  _type: "reference"
AI Update

When you see a reference object with _ref and _type fields, you're looking at an unresolved reference. To get the actual document data, you need to dereference it using the -> operator in your GROQ query.

Here's how to resolve your reference:

*[_type == "yourDocumentType"] {
  ...,
  origin->
}

The -> operator tells GROQ to fetch the complete document that the reference points to. So instead of getting:

{
  "origin": {
    "_ref": "1ec9e722-3636-490d-9094-e102a4fca275",
    "_type": "reference"
  }
}

You'll get the actual document:

{
  "origin": {
    "_id": "1ec9e722-3636-490d-9094-e102a4fca275",
    "_type": "someType",
    "name": "Actual Data",
    // ... other fields from the referenced document
  }
}

Selecting specific fields

If you only need certain fields from the referenced document, you can use a projection:

*[_type == "yourDocumentType"] {
  ...,
  origin->{
    name,
    someField
  }
}

For arrays of references

If your field contains multiple references in an array:

*[_type == "yourDocumentType"] {
  ...,
  origins[]->
}

The Reference Access Operator documentation has more details on how the -> operator works internally—it essentially executes a subquery to fetch the matching document by _id.

I’ve figured I need to use the arrow syntax to access the ref values.
"variations": variations[0].origin -> name
. How would I ensure all origins within the variations array return the name field ?
This is resolved now

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?