👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Querying an array of references and getting both the resolved reference and the _key field.

13 replies
Last updated: Sep 26, 2023
Hi all! When i'm querying an array of references, is there any way to get BOTH the resolved reference and the _key field?When I do this:

products[]
I get the unresolved references with their _key, _ref fields etc.
When I do:
products[]->
, I get the resolved references, without the _key field.I need the _key to have a unique identifier of the array entry in my application.
Aug 29, 2023, 2:46 PM
Can’t you use the _id of the product?
Aug 29, 2023, 2:52 PM
^ i use _id in this situation as well
Aug 29, 2023, 5:06 PM
Yes, I'm now using the _id as the key, but that is not ideal because technically the same product can appear in the array multiple times.
Aug 29, 2023, 6:36 PM
(i also have that issue from time to time 😂 )
Aug 29, 2023, 7:09 PM
This should work:
products[] {
  ...(@->),
  _key,
}

Aug 29, 2023, 7:25 PM
This works, thank you! :heart_hands:
Aug 30, 2023, 8:46 AM
Hi, I tried the above
user S
mentioned, but I still got
null
for the
_key
field, my GROQ looks like this, any idea?
Sep 14, 2023, 6:22 PM
Hi, I tried the above
user S
mentioned, but I still got
null
for the
_key
field, my GROQ looks originally like this, any idea?

_type=='peopleList' => {
    _key,
    _type,
    people[]->{
        _key,
        _type,
        name,
        position,
        bio,
        location,
        image {
            _key,
            _type,
            asset->{
                id,
                url,
                metadata,
                extension
            }
        },
    },
},
Sep 14, 2023, 6:23 PM
Is peopleList a document type? I think the _key field only exists on array entries. For documents you can use the _id as a unique id.
Sep 15, 2023, 2:12 AM
No, it is an object type, I can get the _key field there no problem actually. But I get null value for _key field in the people array which is a reference.
Sep 15, 2023, 5:12 AM
The
_key
is on the reference, not on the referenced document. So you need to merge.
Sep 19, 2023, 9:57 AM
Here's one way:
"people": people[] {
  _key,
  ...(@-> {
    _type,
    name,
    position,
    bio,
    location,
    // etc.
  })
}
For each ref, it merges in
@->
, which will resolve to the referenced document.
Sep 19, 2023, 9:58 AM
user S
Thanks you so much! This works!
Sep 26, 2023, 8:46 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?