Programmatically adding reference arrays in Sanity with correct _type

5 replies
Last updated: Jun 14, 2022
So I'm trying to programmatically add an array of references to my "auction" types. So far I've got:

const patch = await sanityClient
  .patch(auction._id)
  .set({ creators: [] })
  .append('creators', [{ _type: 'reference', _ref: creator._id }])
  .commit();
However, when I look in Sanity, I see:

Furthermore, when I instead append
[{ _type: 'creator', _ref: creator._id }]
, Sanity explores with a Desk tool error. Unsure what to do here. 😕
I don't really understand because the docs say the
_type
should be `reference`: https://www.sanity.io/docs/reference-type#e97572ca6050
When I use the UI to add a reference to a creator, I see the document resolves as follows:

creators:[] 1 item
0:{} 3 items
_type:creator
_key:efe8806304af
_ref:00b4b61b-03f8-4587-9d00-68367fc80b5b
Any help adding reference arrays programmatically?

Edit, edit, edit: The docs may be wrong. The reference lands intact if it's of type
whateverTypeTheReferenceRefersTo
AND if I have
autoGenerateArrayKeys: true
.
AI Update

Looking at the official Sanity documentation on creating references programmatically, you should indeed use _type: 'reference' when creating references programmatically, exactly as documented.

However, the real issue you're experiencing is almost certainly related to the missing _key field, not the _type field. Every item in a Sanity array requires a unique _key, and this is what's likely causing your Desk tool errors.

Here's the correct way to add reference arrays programmatically:

import {randomKey} from '@sanity/util/content'

const patch = await sanityClient
  .patch(auction._id)
  .set({ creators: [] })
  .append('creators', [{ 
    _type: 'reference', 
    _ref: creator._id,
    _key: randomKey(12)  // This is crucial!
  }])
  .commit();

Or enable automatic key generation in your client configuration:

import {createClient} from '@sanity/client'

const sanityClient = createClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset-name',
  useCdn: false,
  apiVersion: '2023-05-03',
  token: process.env.SANITY_SECRET_TOKEN,
  autoGenerateArrayKeys: true  // This handles _key automatically
})

Why you saw _type: 'creator' in Studio:

When you inspected the UI-created reference and saw _type: 'creator', you may have been looking at a dereferenced version or a display artifact in Studio. The actual stored data format uses _type: 'reference' as specified in the reference type documentation.

There's also a scenario where _type would be the document type: if your schema allows references to multiple document types in an array, but that doesn't appear to be your case based on your description.

Summary: Stick with _type: 'reference' as documented, but make sure you're either manually adding _key fields or enabling autoGenerateArrayKeys: true. The missing _key is what's breaking things, and enabling auto-generation (as you discovered in your edits) is what made it work.

Show original thread
5 replies
user Y
please try to keep all of the information relating to your issue in a single thread. It allows us to keep track of any additional context and keeps the main thread less cluttered. Thanks!
You're right! Sorry about that!
No worries! Many thanks, again!
Does the schema for this array allow for multiple types of documents to be referenced? If so, I believe the issue is that you need to specify
_type
as the type of the document being referenced so that the Studio UI knows what to render.
To break it down a bit further, if your schema looks like this:

{
  name: 'creators',
  title: 'Creators',
  type: 'reference',
  to: [{ type: 'creator' }]
}
You can programmatically set a reference like so:

const patch = await sanityClient
  .patch(auction._id)
  .set({ creators: [] })
  .append('creators', [{ _type: 'reference', _ref: creator._id }])
  .commit();
However, if it looks like this:

{
  name: 'creators',
  title: 'Creators',
  type: 'reference',
  to: [{ type: 'creator' }, { type: 'person' }]
}
This should work (so long as you're
autogenerating your array keys):
const patch = await sanityClient
  .patch(auction._id)
  .set({ creators: [] })
  .append('creators', [{ _type: 'creator', _ref: creator._id }])
  .commit();
Let me know if that's not the behavior you're getting though!
My schema only allows for one type. It didn't work with
_type: 'reference'
. It worked with
_type: 'creator'
. However, it may have been the key auto-generation that was messing everythign up.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?