How do I query referenced document fields within an array of objects in Sanity with GROQ?

4.2k views Asked by At

I have a document which has an array of objects of which one of the fields is a reference to another document. The following query returns the referenced document _id and _type only, and I need other fields from those documents.

// GROQ query
*[slug.current == $slug]{
  title,
  slug,
  objectArray
}

This results in:

"result": [
0: {
  "title": "Test Document"
  "slug": {
    "_type": "slug"
    "current": "test-document"
    }
  "objectArray": [
    0: {...}
    1: {
      "_key": "583ec1dee738"
      "_type": "documentObject"
      "objectTitle" : "Test Object"
      "documentReference": {
        "_ref": "2f9b93b4-4924-45f2-af72-a38f7d9ebeb4"
        "_type": "reference"
        }
      "booleanField": true
      }
    ]
  }
]

documentReference has its own set of fields (ie. title) in the schema which I need to be returned in my query.

How do I do this?

I have looked at the Sanity documentation at joins and object projections, but I cannot get the syntax right for when the reference is within an array of objects.

1

There are 1 answers

4
Alexander Staubo On

You need to do a join on the reference:

*[slug.current == $slug] {
  title,
  slug,
  objectArray[] {
    documentReference->
  }
}

The syntax objectArray[] can be thought of as "for each element", and -> does a join to look up the referenced document. In other