🎤 Builder Talk: The Story Behind Lady Gaga’s Digital Experience – Register now

How to Update a User Document Using the @Sanity Client

11 replies
Last updated: Aug 2, 2022
Hi guys, Im trying to get a handle on how to use the @sanity/client to create a document and also update the user document with the reference to this document. So far I’ve managed to create the document however getting the client to add in the ref to this document id is proving a little difficult.
Here is my code trying to do the following, taking the id after the document is created and patching the user document:

const _addCalc_ = _async_ ()
=>
{

_return await getClient_(_false_)

_.create_({

..._calcDetails_,

__type_:
"calculator",

})

_.then_((_res_)
=> _addRefToUser_(_res_));

};

_addCalc_();


const _addRefToUser_ = _async_ (_res_)
=>
{

_await getClient_(_false_)

_.patch_("user.cf26c3dd-7c63-4fcc-b936-6069b05213a7")

_.set_({ _calculator_: _res._id_ })

_.commit_()

_.then_((_res_)
=> _console.log_(_res_));

};

}
I am able to have the document update the user detail but its giving me an error on the type as its showing as a string. I’m sure I’m missing a better way of doing this process, any help would be appreciated.
Aug 1, 2022, 10:53 PM
Can you try changing to the following?
const addCalc = async () =>
  await getClient(false)
    .create({ ...calcDetails, _type: 'calculator' })
    .then(
      async res =>
        await getClient(false)
          .patch('user.cf26c3dd-7c63-4fcc-b936-6069b05213a7')
          .set({
            calculator: {
              _ref: res._id,
              type: 'reference',
            },
          })
          .commit()
          .then(res => console.log(res))
    );

Aug 1, 2022, 11:10 PM
That seems helpful - but I’m now getting an error ClientError: Key “type” not allowed in ref
Aug 1, 2022, 11:16 PM
What does your calculator schema look like in your user document?
Aug 1, 2022, 11:18 PM
_import_ { Document } _from_ "./schemaTypes";


export
_default_ <Document>{

name: "calculator",

title: "Calculator",

type: "document",

fields: [

{

name: "vehicle",

title: "Vehicle",

type: "string",

},

{

name: "distance",

title: "Distance",

type: "string",

},

{

name: "fuelEfficiency",

title: "Fuel Efficiency",

type: "string",

},

{

name: "eVehicle",

title: "E-Vehicle",

type: "string",

},

{

name: "activeStep",

title: "Active Step",

type: "number",

},

],

};
Aug 1, 2022, 11:19 PM
What does the user document that references this calculator look like?
Aug 1, 2022, 11:44 PM
import { Document } from "./schemaTypes";

export default <Document>{
  name: "user",
  title: "User",
  type: "document",
  fields: [
    {
      name: "name",
      title: "Name",
      type: "string",
    },
    {
      name: "email",
      title: "Email",
      type: "string",
    },
    {
      name: "image",
      title: "Image",
      type: "url",
    },
    {
      name: "calculator",
      title: "Calculator Data",
      type: "reference",
      to: { type: "calculator" },
    },
  ],
};
Aug 1, 2022, 11:53 PM
I thinik I figured it out…need to use _type
Aug 1, 2022, 11:55 PM
thanks for your help!
Aug 1, 2022, 11:55 PM
Fantastic!
Aug 2, 2022, 5:48 AM
Is this more or less the correct way to link the records?
Aug 2, 2022, 3:23 PM
It is!
Aug 2, 2022, 4:42 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?

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
Rendering nested block contentJan 18, 2021
Warning: Data for Page Exceeds the Threshold of 128 kBAug 17, 2022
List Arrays - Is it Possible to Fill a List Array Within a Schema Asynchronously?Mar 16, 2021
Custom Document Views - Is it Even Possible to Use the Structure Builder?Apr 21, 2022
TypeError: Cannot Read Properties of Null (Reading 'jsonType')Sep 28, 2022
Error in custom validation rule for schema in Slack threadAug 18, 2023
GraphQL query resolving references on a _raw field in GatsbyMay 17, 2022
How to populate a list of values in a Sanity schema using a separate fileSep 6, 2021
How to fetch an array of images using groq in Sanity.ioMay 21, 2023
Is there a way to write a groq query that checks if a boolean is true, and if so, returns an array of referenced documents?...Feb 1, 2021

Related contributions

Turbo Start Sanity
- Template

The battle-tested Sanity template that powers Roboto Studio's websites

Go to Turbo Start Sanity

Schema UI - Next.js Sanity Starter
- Template

A Next.js starter template with Next.js 15, Tailwind CSS, shadcn/ui, and Sanity CMS with Live Editing. Get production-ready React components with matching Sanity schemas and queries. Build dynamic pages faster while keeping full control over customization.

Serge Ovcharenko
Go to Schema UI - Next.js Sanity Starter

The Swaddle
- Made with Sanity

A new brand identity to represent a more mature company, to signify The Swaddle’s evolution from publisher to production house, combined with an easier to navigate platform that can surface multiple content types - drawing readers through The Swaddle’s content offering.

Nightjar
Go to The Swaddle