mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
1.1 KiB
1.1 KiB
Add Item To An Array Of References In Sanity
Let's say we have an existing record in our Sanity dataset. The schema for that record allows for an array of references to another type of record. As part of programmatically importing some data, we need to tie some records together by adding to that array of references.
We've already set up our Sanity client
(via the JavaScript SDK). We have an _id for the record we want to patch. We
have a resourceId for the resource that we want to reference in the array.
Here is how we perform that patch:
await sanityClient
.patch(_id)
.setIfMissing({resources: []})
.append('resources', [{_type: 'reference', _ref: resourceId}])
.commit({autoGenerateArrayKeys: true})
- We give it the
_idof the record we want topatch. - We set our array of
resourcesto an empty array ([]) if it hasn't already been set. - We
appendto theresourcesarray with an array containing a single item, a reference to our resource. - We
committhe changes with the directive that Sanity should auto-generate the_keyvalue for any new array items.