πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Querying images used in a document in a schema-agnostic way in Slack thread.

4 replies
Last updated: Oct 8, 2023
Hey folks - I'm building a custom color input with recommended swatches based on the images used in a document.
It's working great - except I haven't been successful in querying images used in a document. It'd be easy to make it schema specific, but I would like this to operate agnostic of the document schema, especially since my project uses portable text with image fields extensively.

I've tried
*[_type == 'sanity.imageAsset' && references($docId)]
but it runs an empty array despite at least one image being used on my document.
Seems like
sanity.imageAsset
isn't returned in this way whatsoever.
Is there any method for doing this sort of thing or am I right out of luck? Thanks!!
Oct 7, 2023, 10:48 PM
Hey
user Q
. The query you wrote means "if type is
sanity.imageAsset
and it references the document ID", which is the opposite order of what you want, I believe.I'm going out on a limb here, but maybe
*[_type == "sanity.imageAsset" && count(*[_id == $docId && references(^._id)]) > 0]
might work
Oct 8, 2023, 12:01 AM
You are amazing. Thank you!!
Oct 8, 2023, 12:03 AM
I had some variants of that but didn't attempt the greaterThan properly
Oct 8, 2023, 12:03 AM
Haha I'm glad it worked
Oct 8, 2023, 12:16 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?