How to fetch referenced documents properties in a JavaScript client query.
16 replies
Last updated: Dec 4, 2020
G
when using the javascript client and I fetch a "location" document with referenced "labels" array, the labels array doesn't contain most of the referenced documents properties. How do I get it to include them?
Dec 3, 2020, 10:17 PM
A
Is your query using the dereferencing operator (
->)?
Dec 4, 2020, 2:04 AM
G
I tried, that didnt work at all
Dec 4, 2020, 6:41 AM
G
query looks like this
Dec 4, 2020, 6:41 AM
G
*[_type == "location"]{ _id, name, description, image, location, characters, labels }
Dec 4, 2020, 6:41 AM
G
schema for locations is like this
Dec 4, 2020, 6:42 AM
G
{ title: 'Location', name: 'location', type: 'document', fields: [ { name: 'name', Title: 'Name', type: 'string' }, { name: 'description', Title: 'Description', type: 'text' }, { name: 'location', Title: 'Location', type: 'geopoint' }, { name: 'image', title: 'Image', type: 'image' }, { title: 'Characters', name: 'characters', type: 'array', of: [{ type: 'reference', to: [{type: 'character'}] }] }, { title: 'Labels', name: 'labels', type: 'array', of: [{ type: 'reference', to: [{type: 'label'}] }] } ] }
Dec 4, 2020, 6:42 AM
G
at the moment I get labels in the result but its only the meta keys
Dec 4, 2020, 6:43 AM
G
when i change it to labels-> I get no labels at all
Dec 4, 2020, 6:44 AM
G
Would you expect this to work?
Dec 4, 2020, 8:31 AM
G
*[_type == "location"]{ _id, name, description, image, location, characters, labels-> }
Dec 4, 2020, 8:31 AM
M
Hi Richard, could you try something like this?
*[_type == "location"]{ _id, name, description, image, location, characters, "labels": labels[]->{ ... } }
Dec 4, 2020, 12:16 PM
P
Hi Richard, could you try something like this?
*[_type == "location"]{ _id, name, description, image, location, characters, "labels": labels[]->{ ... } }
Dec 4, 2020, 12:16 PM
R
perfect! that works thanks!
Dec 4, 2020, 12:24 PM
R
is that approach documented anywhere? I don't recall seeing that anywhere
Dec 4, 2020, 12:24 PM
P
You could probably also just use
labels[]->alone - the issue was there: it's an array so it needs
[]๐ You can find some examples over here: https://www.sanity.io/docs/query-cheat-sheet#object-projections-4ff061cc51e4
Dec 4, 2020, 12:31 PM
R
oh thats handy thanks!
Dec 4, 2020, 12:33 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.