Search code examples
sanity

How to increment property per document in Sanity?


We are making a system where users can submit orders. Orders have an incrementing property deliveryNumber; a new order should get a deliveryNumber that is one higher than the previous order.

Is there any built-in support for this in Sanity?
If not, how can we achieve this, without risking collisions due to race conditions?


Solution

  • I just rediscovered this question and thought I should update it, as there has (for some time now) been a way to do exactly what you're asking:

    Here's an example using the Sanity Javascript client:

    const sanityClient = require('@sanity/client')
    const client = sanityClient({
      projectId: 'my-project-id',
      dataset: 'my-dataset',
      token: 'sanity-auth-token',
      useCdn: false
    })
    
    client
      .patch('order-123') // Document ID to patch
      .inc({deliveryNumber: 1}) // Increment field by 1
      .commit() // Perform patch and return a promise
      .then(updatedOrder => {
        console.log('Order delivery number', updatedOrder.deliveryNumber)
      })
      .catch(err => {
        console.error('Ouch. Update failed: ', err.message)
      })

    If you're not accessing Sanity via Javascript, you can do the same thing using the HTTP API.