🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to get the titles of tags attached to stories in Sanity.io

3 replies
Last updated: Jun 11, 2020
I'm struggling with what I feel certain is a very basic query. So maybe someone will be able to give me a quick easy answer!
I have documents of
_type == "story"
. Each Story has a field of
tags
which is an array of references to document
_type == "storyTag"
.
Story schema:

export default {
  name: 'story',
  title: 'Story',
  type: 'document',
  fields: [
    {
      name: 'author',
      title: 'Author',
      type: 'string',
    },
    {
      name: 'tags',
      title: 'Tags',
      type: 'array',
      of: [{ type: 'reference', to: { type: 'storyTag' } }],
    },
...
}
Story Tag schema:

export default {
  name: 'storyTag',
  title: 'Story Tag',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string',
    },
  ],
}
I want to query my dataset and get all the stories, with the titles of the tags attached to it.

Using:

`*[ _type == "story" ]{
   _type,
  "title": author,
  tags
}`
gets me the stories with an array of tags attached, but that array looks like this:

[{
_key: "b251db713b80"
_ref: "17d1190e-c8d2-40a4-8e12-97875ed95bf1"
_type: "reference"
}]
How can I get the title of the tags? I've tried a variety of different queries but none have worked - I'm sure I'm missing something simple, but any help would be much appreciated.
🙏
Jun 11, 2020, 2:49 PM
Still new to this, but does this do it?
*[ _type == "story" ]{
   _type,
  "title": author,
  "tags": tags[]->title
}
Jun 11, 2020, 3:03 PM
user L
honestly - I thought I'd tried exactly that, but there must have been something wrong because this works like a charm. Thank you for taking the time!
Jun 11, 2020, 3:06 PM
np, i recently went down the "how do i resolve all arbitrarily nested references" path, this was a solution if i knew all the nested paths (which I didnt)
Jun 11, 2020, 3:08 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.

Was this answer helpful?