I had a hard time figuring out how to handle bulk updates (patches) for articles in Sanity. While there is documentation about modifying general arrays and text fields, there was nothing about modifying related fields in bulk.
Through a bit of trial and error I figured out that it was relatively similar to a create call.
The safest way to make a bulk update is using transactions. Set up your async function with by calling sanityClient.transaction(). You can then chain all your patch modifications together thanks to the Sanity client.
In the snippet above I am adding a predefined relational reference at the end of the array field.
Commonly you won’t need to modify all of your articles. Below is a simple example of how you can tag articles containing a keyword by running a patch transaction using the Sanity client.
Now import the Sanity client.
Running the Update with TS Node Dev
To run this, you could set up a simple typescript project. Run ts-init and install the necessary dependencies, namely the Sanity client.
Run npx ts-node transform.ts and your articles will be updated using a Sanity client patch transaction.