Programmatically adding reference arrays in Sanity with correct _type
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 thread5 replies
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.