๐Ÿ‘€ Our most exciting product launch yet ๐Ÿš€ Join us May 8th for Sanity Connect

How to create a new document and set a reference in an array using the JavaScript API.

3 replies
Last updated: Jan 9, 2024
With the javascript API, how do I create a new document and set a reference that is a member of an array? I've tried a lot of things and gotten errors, now it's just failing silently.
I understand that I need to set the _ref to the actual ref of the referred to item and I'm setting a uuid _key.

Both of the following fail.
finalistCategory
is the name of the field and it should get populated, one item in an array, and they should be refs to
awardCategory


 finalistCategory: [
      {
        _id: "6c3c48e1-91b1-44b0-bcdc-640037cfabcd",
        _type: "reference",
        _key: "a18b3d20-fd0c-4aeb-8b72-924bcd90d0e1"
      },
    ],

finalistCategory: [
      {
        awardCategory: {
          _id: "6c3c48e1-91b1-44b0-bcdc-640037cfabcd",
          _type: "reference",  
          _key: uuidv4().toString(),
        },
      },
    ],
I wonder if part of the issue is something to do with I'm using
_sanityClient_._createOrReplace_
and maybe I need to be doing something with
patch
as per https://www.sanity.io/docs/js-client#patchupdate-a-document but patch seems to work only on existant docs....
Jan 9, 2024, 2:49 PM
replace
_id
with
_ref

      {
        _ref: "6c3c48e1-91b1-44b0-bcdc-640037cfabcd",
        _type: "reference",
        _key: "a18b3d20-fd0c-4aeb-8b72-924bcd90d0e1"
      },
Jan 9, 2024, 3:06 PM
Oh, thank you! I'd been bashing my head on this for a while
Jan 9, 2024, 3:08 PM
And I'd just overlooked that, I knew it should be _ref, at least in theory. Thanks again
Jan 9, 2024, 3:09 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?