3

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 Answer 1

5

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

4
  • Thanks, but unfortunately this just returned NULL for each item in the array. Does it mean that it isn't possible to query references within an array of objects?
    – Anthony
    Apr 8, 2022 at 14:26
  • 4
    Instead of objectArray[]-> can you please try objectArray[]{...,documentReference->}?
    – Geoff Ball
    Apr 8, 2022 at 18:01
  • That's it! That returned all the fields and is exactly what I needed. Thank you!
    – Anthony
    Apr 8, 2022 at 21:19
  • Good catch, @GeoffBall. Fixed my reply. Apr 11, 2022 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.