Querying for documents that use a specific image/asset and retrieving the slug from the parent document.

7 replies
Last updated: Jan 17, 2023
Hey! I’m trying to query for document(s) that use a specific image/asset – so I can grab the slug from the “parent document”.Something like this:

  const home = await client.fetch(groq`
    *[_id == "singleton-home"]
        "parent": *[_type == 'some_document_type' && references(^.asset._id)]{
I’m assuming maybe I’m grabbing the wrong _id here – as I want to compare the _id from the image/asset and not from the ‘singleton-home’ document.
Is what I’m trying to do possible / Can someone help me with this?:)
Jan 16, 2023, 3:57 PM
Could you try.
*[_type == parentDoc && _id == "singleton-home"]{
image ...
Jan 16, 2023, 6:34 PM
I realize that I may have worded my question a bit poorly – let me try to rephrase!
In my ‘singleton-home’ document I have an array of images. When querying for this array I would like to also look for other documents that use the same images/assets, and get the slug for those pages along with the images themselves.

I could of course restructure the studio to make it work, but just wonder if there is a quick and slick groq-way of doing it without changing anything in the studio:-)
Jan 16, 2023, 6:39 PM
This is the part I’m trying to get to work:
        "parent": *[_type == 'some_document_type' && references(^.asset._id)]{
Jan 16, 2023, 6:40 PM
I see now. I wasn't sure what you meant by parent. Hmm that is a tricky one. If it is statically generated like with next js you could just run a 2nd query and store the reference id in a variable a combine them into the same object. I can't see a way to do it without knowing the ref ID ahead of time.
Jan 16, 2023, 6:51 PM
An image’s data looks something like this:
<fieldname>: {
  _type: 'image',
  asset: {
    _type: 'reference',
    _ref: <id-of-asset-document>
In your subquery for your parent documents, you’re inside the scope of the
field, so you want to use this:
'parent': *[_type == 'some_document_type' && references(^.asset._ref)].slug
Jan 17, 2023, 9:17 PM
Works like a charm, thanks a lot!
Jan 17, 2023, 9:37 PM
You’re welcome!
Jan 17, 2023, 9:39 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?