How to Expand References Using Sanity's GROQ Queries

Jordan McRae

Co-founder

3 min

Article Banner

If you're learning how to use Sanity's GROQ query language, you've probably run into a situation where the data you're receiving has a reference in it. Whether it's an object reference, an array of references, or nested references, we'll show you how to expand them inside of your GROQ query.

Expanding an Object Reference

Let's assume we have a query that grabs an article and that it has a topic attached to it. If the topic is a reference, we can expand it like this:

1const query = groq`*[_type == 'article'][0] {
2  ...,
3  topics->
4}`;

You can see in the query above that we have added an arrow -> next to our topic field in the GROQ query. This is telling Sanity that we want to expand the reference. In other words, we want Sanity to give us all of the data and fields that this article's topic has.

The second piece in the query above is the spread operator (...,). What this tells Sanity is that in our main article query, we want to return all of the fields that an article has. If we were to remove this, we would only receive the topic inside of the article object since it would be the only field we have defined in the query.

Expanding an Array of References

Next, let's assume that we have a query that grabs an article again. This time instead of an article having only one topic associated with it, our article schema has changed and now it can have multiple topics associated with it. We would expand the array of references like this:

1const query = groq`*[_type == 'article'][0] {
2  ...,
3  topics[]->
4}`;

Similar to the first query we saw, you can now see we are declaring that topics are an array of references by adding square brackets [] after the topic field.

Expanding Nested References

As a final example, let's say that a topic has a reference to tags that we want to expand. If we were to run the queries above, tags would now be references inside of our topics data. It's basically the same situation we were facing when we had to expand topics, but now we need to expand tags inside of a topic like this:

1const query = groq`*[_type == 'article'][0] {
2  ...,
3  topics[]-> {
4    ...,
5    tags[]->
6  }
7}`;

Now we should see topics and tags both expanded, and all of the fields associated with them.

Important Notes

  1. If you are expanding a reference and you define fields inside of {}, you must add ..., if you want all of the fields to return with your data. Otherwise, you can define each field individually that you want to return from your Sanity query.
  2. You must expand nested references this way as deep as they go. There is currently no way to automatically expand all nested references without explicitly defining them in your query.