As far as i know, there is no built in support for incrementing properties for each new document yet. However, you can achieve it on your own for documents with only one incrementing property (or if the incrementing properties can all be deduced from a single, incrementing property).
Method
To do this we take advantage of the fact that when you create a new document, you can set the _id
instead of letting Sanity generate it for you. If you try to create a document with an _id
that is already used for another document, the query will fail. We use this as a mechanism to guard against race conditions.
For the use case in quesition, we need to do three things:
- Fetch the
deliveryNumber
of the last created order (see this answer)
- Increment by one to get the next
deliveryNumber
- Create a new order with the same value for
_id
and deliveryNumber
If two orders are placed at the same time, so that there is an attempt to create two orders with the same deliveryNumber
, the last query that is processed by Sanity will fail because is has the same _id
as the first one. As long as it doesn't fail, every order should have a uniqe deliveryNumber
one higher than the previos one.
When it fails
If the orders are created as a result of user interaction, I suggest letting the user know that it failed and ask them to try again. This will not happen often, and almost certainly not twice in a row.
If, however, you must programatically ensure that you try again until you succeed, I suggest backing off a randomized amount of time (that increases exponentially each time it fails), before trying again.
Viability
The more frequently orders are created, the less viable this solution is. For most systems I assume this is unlikely to fail at all.