How to Update a User Document Using the @Sanity Client
Looking at your code, the issue is that when you use .set() with a reference field, you need to provide a proper reference object structure, not just the ID as a string. Here's how to fix it:
const addRefToUser = async (res) => {
await getClient(false)
.patch("user.cf26c3dd-7c63-4fcc-b936-6069b05213a7")
.set({
calculator: {
_type: 'reference',
_ref: res._id
}
})
.commit()
.then((res) => console.log(res));
};The key change is structuring the reference as an object with _type: 'reference' and _ref: res._id instead of just passing res._id directly. This is the proper structure for strong references in Sanity.
However, if your schema defines calculator as an array of references (which is common), you'll want to use the append operation instead:
const addRefToUser = async (res) => {
await getClient(false)
.patch("user.cf26c3dd-7c63-4fcc-b936-6069b05213a7")
.setIfMissing({ calculator: [] })
.append('calculator', [{
_type: 'reference',
_ref: res._id,
_key: res._id // good practice for array items
}])
.commit()
.then((res) => console.log(res));
};The patches documentation explains how different operations work. The setIfMissing ensures the array exists before appending, and append adds the new reference to the array.
Also, a small optimization - you can simplify your _addCalc_ function since .then() already returns the result:
const _addCalc_ = async () => {
const res = await getClient(false).create({
...calcDetails,
_type: "calculator",
});
return addRefToUser(res);
};This approach is cleaner and handles the async flow more naturally than mixing await with .then().
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.