Get a peek at our latest innovations at Sanity Product Day on Dec 8th →

Mutate, set or change values deep within documents

By Pål Smitt-Amundsen

JS/Node example of using the /mutate API

mutate.js

const fetch = require("node-fetch");

// set SANITY_PROJECT_ID/SANITY_KEY/SANITY_DATASET in .env file
require("dotenv").config();

// https://www.sanity.io/docs/http-mutations
// https://www.sanity.io/docs/http-patches
// https://www.sanity.io/docs/json-match

async function mutate(mutations) {
  const result = await fetch(
    `https://${process.env.SANITY_PROJECT_ID}.api.sanity.io/v2021-06-07/data/mutate/${process.env.SANITY_DATASET}`,
    {
      headers: {
        "content-type": "application/json",
        Authorization: `Bearer ${process.env.SANITY_KEY}`,
      },
      body: JSON.stringify(mutations),
      method: "POST",
    }
  );

  const json = await result.json();
  return json;
}

const mutations = {
  mutations: [
    {
      patch: {
        id: "373a5de5-3d0e-4146-bbaa-1a38a26a447d",
        set: {
          '[_id == "373a5de5-3d0e-4146-bbaa-1a38a26a447d"].alternatives[17].title.nn':
            "Noreg",
        },
      },
    },
  ],
};

mutate(mutations);

If you need to set, mutate or alter values deep into an array, in a document, I find @sanity/client cumbersome to use as you cannot target array members with the _key.

But fear not! The mutate endpoint to the rescue! With a little help from http-patches and json-match you can update values with laser  precision like:
[_id == "373a5de5-3d0e-4146-bbaa-1a38a26a447d"].alternatives[17].title.nn

Used in my case to do a machine translation between languages. Here’s an example to get you started with Node (or js).


EDIT: I've just learned that you can do the same with the JS client:
client.patch('296499fa-ec36-45ca-b1bd-db0e356b3923')
.set({'alternatives[0].title.nn':'Yep', })
.commit()
.then(r => {console.log(r); })

Contributor