Difficulty accessing asset properties in a query, but issue was resolved.
11 replies
Last updated: Nov 3, 2022
M
Hey folks!I’m trying to pull an array of projects from a reference document and can’t work out how to access the asset properties.
In this query, the assetGroup is returned, but none of the asset metadata like its url is.
In this query, the assetGroup is returned, but none of the asset metadata like its url is.
const query = `{"data": *[_id == "projectsArray"] { "projects": projects[]{ "builtAt": project->builtAt, "description": project->description, "id": project->_id, "slug": project->slug, "title": project->title, "year": project->year, "cover": project->cover { "id": cover.asset->assetId, "url": cover.asset->url, "meta": cover.asset->metadata }, "assets": project->assets[]{ assetGroup, "url": asset->url } } }}`
Nov 3, 2022, 9:45 PM
Hey Mikhail! You don't need to expand your reference each time. You can do:
projects[]->{ builtAt, description, id, slug, title, year, cover->{ url, //other fields }, assets[]{ 'url': asset->url //other fields } }
Nov 3, 2022, 9:52 PM
M
user M
Hmm. This returns an empty object for each project.Nov 3, 2022, 10:00 PM
Can you share your schema?
Edit: Do you have this wrapped in an object called project? if so:
Edit: Do you have this wrapped in an object called project? if so:
projects[]{ project->{ builtAt, description, id, slug, title, year, cover->{ url, //other fields }, assets[]{ 'url': asset->url //other fields } } }
Nov 3, 2022, 10:01 PM
M
user M
This throws an error, wrapped or unwrapped within the query.A simple test version returned a 400:const query = `{"projects": *[_id == "projectsArray"] { projects[]{ project->{ builtAt, description, id, slug, title, } } }`
Nov 3, 2022, 10:06 PM
M
https://github.com/m-shum/mshumakov-cms/tree/main/schemas This is the schema section of the repo, and this is the document I’m pulling: https://github.com/m-shum/mshumakov-cms/blob/main/schemas/documents/projectsArray.js
Nov 3, 2022, 10:07 PM
Given that schema, that first query should work for you. Can you share the full query that you added that to?
Nov 3, 2022, 10:11 PM
M
Currently all I’ve got it this:
Nov 3, 2022, 10:12 PM
M
const query = `{"projects": *[_id == "projectsArray"]{ projects[]{ project->{ slug, cover{ asset->{url} }, assets[]{ asset->{url} } } } }}`
Nov 3, 2022, 10:12 PM
M
Nov 3, 2022, 10:12 PM
M
user M
I got my head around in the end, thank you so much! All works now 🙂Nov 3, 2022, 10:18 PM
Oh great! I was just trying to put together a query link for you. Glad you got it sorted!
Nov 3, 2022, 10:19 PM
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.