Adding reference arrays programmatically in Sanity.io

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
.
Jun 13, 2022, 8:26 PM
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!
Jun 13, 2022, 8:31 PM
You're right! Sorry about that!
Jun 13, 2022, 8:35 PM
No worries! Many thanks, again!
Jun 13, 2022, 8:37 PM
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!
Jun 13, 2022, 8:48 PM
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.
Jun 14, 2022, 2:42 AM

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?