APIs and SDKs

Creating and updating documents with @sanity/client

Learn how to create, update, and patch documents with @sanity/client, including array manipulation, chained operations, and conditional updates.

The @sanity/client library provides methods for creating and modifying documents in your dataset. This guide covers the create, createOrReplace, createIfNotExists, and patch methods with practical examples for each.

Validation is client-side only

Prerequisites

All mutation methods require an authenticated client with a write token and return promises that resolve with the created or updated document. See Getting started with @sanity/client for setup instructions.

Creating documents with client.create()

The create() method creates a new document in your dataset. Sanity automatically generates a unique _id for the document unless you provide one.

You can also specify a custom document ID:

Creating or replacing with client.createOrReplace()

The createOrReplace() method creates a new document or completely replaces an existing one if a document with the specified _id already exists. This is useful for idempotent operations where you want to ensure a specific document state.

Creating if not exists with client.createIfNotExists()

The createIfNotExists() method creates a document only if no document with the specified _id exists. If the document already exists, the operation does nothing and returns the existing document.

This method is particularly useful for initialization scripts or ensuring default documents exist without overwriting user modifications.

Patching documents with client.patch()

The patch() method lets you update specific fields in an existing document without replacing the entire document. You can chain multiple operations together to perform complex updates.

The commit() method executes the patch operation. You can chain multiple patch operations before calling commit().

Setting fields with .set()

The set() method sets or overwrites field values. You can set multiple fields at once or use dot notation to set nested fields.

Setting only if missing with .setIfMissing()

The setIfMissing() method sets field values only if the fields don't already exist or are null. This is useful for setting default values without overwriting existing data.

Removing fields with .unset()

The unset() method removes fields from a document. You can remove multiple fields by passing an array of field paths.

Incrementing and decrementing with .inc() and .dec()

The inc() and dec() methods increment or decrement numeric field values. These operations are atomic and useful for counters, view counts, or other numeric tracking.

Conditional patches with .ifRevisionId()

The ifRevisionId() method ensures that a patch only applies if the document's current revision matches the specified revision ID. This prevents race conditions and ensures you're updating the version of the document you expect.