✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to generate sequential order numbers in Sanity.io using frontend or backend

4 replies
Last updated: Dec 20, 2022
Dear support, comunity,what is easiest way to get/write next number of array - field "orderNumber"
Example of object order:
{
"_createdAt": "2022-12-14T19
:04:58Z", "_id": "4db5796f-ed83-411d-b419-bf668206b3ce",
"_rev": "j1tWZCfjdAwUaXU7wQg1DG",
"_type": "order",
"_updatedAt": "2022-12-14T19
:14:25Z", "note": "erer",
"orderNumber": 2300000001
}

I would like to write next number of field "orderNumber" in the moment when i run function "createOrder"
function createOrder() {

const doc = {
_type: 'order',
note: 'První poznámka objednávky',
order_number: novaObj,
}
console.log(novaObj);
client.create(doc).then((res) => {
console.log(
Objednávka byla vytvořena , document ID is ${res._id}
) });
}
----

What i found
https://www.sanity.io/docs/groq-functions#03c444f2caf3
math::sum(<array[number]>) <number|null>
and
https://www.sanity.io/docs/initial-value-templates
Thank you
Dec 16, 2022, 2:28 PM
Hey
user M
! What are you basing your order numbers on? If you're looking to create a sequential order number, it'd probably be easiest to use the JS client to fetch the most recent order number, then set the order number in your document to the previous order number + 1. You can also use something like the
uuid
npm package to generate unique numbers if that's what you're looking for!
Dec 16, 2022, 9:48 PM
Hey,
user M
, thank you for fast reply. Yes, thats what i want to. But are u sure, that is good idea to fetch last order and sum +1 at frontend and after that send to backend? I wanted to do that, but one of my friend stop me, dont do that. Backend need to give you right order, dont create order on the frontend.This article i cant use for that
https://www.sanity.io/docs/groq-functions#03c444f2caf3 ?
Thank you for any ideas
Dec 17, 2022, 9:48 AM
Yeah, I suppose you could use that function to calculate your order number. It would still require you to fetch the previous order number and add to it. You'd just be doing it in a single step.
Dec 19, 2022, 5:32 PM
Thank you, I really preciated your answer
user M
, but if many customers use this flow, so in same moment wanna create order, it couldnt be like that. I tryied it - fetch last order, sum, create order at FE, send to BE a do it again, i get same number of order. API/DB probably need more time if u wanna use it same time to use this function. Are u really sure that it can be like that? I cant use any other function at BE to do sum with last value of order in last document?Thakn you
Dec 20, 2022, 9:04 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?