How can i generate automated ID when adding items to my collection (to be in numbers)

hi all,

i tried the below code from previous talks but it didn’t work I tried in-home and backend but unfortunately didn’t work if you kindly can guide me that will be great

//inside data.js
import wixData from ‘wix-data’ ;
export function set_beforeInsert ( item , context ) {
return wixData . query ( “set” )
. descending ( “id” )
. limit ( 1 )
. distinct ( “id” , { “suppressAuth” : true , “suppressHooks” : true })
. then ( r => {
let lastItem = r . items [ 0 ];
let id ;
lastItem ? item . id = lastItem + 1 : item . id = 1 ;
return item ;
})
}

The best way to do it is by using the _id field itself (this way you can assure there will never be duplicates.
But the _id field is of type string which means that 2 will be bigger than 10.
So in order to deal with that you should create them like:
0000000001
0000000002

0000000010

Add all the items programmatically (with .insert() and specifying the _id)

For example:

export function set_beforeInsert(item, context) {
return wixData.query("set")
 .descending("_id")
 .limit(1)
 .distinct("_id", {"suppressAuth": true, "suppressHooks": true})
 .then(r => {
  const newIdNumber = r.totalCount > 0 ? Number(r.items[0]) + 1 : 1;
  item._id = newIdNumber.padStart(10, "0");//here you're adding the leading zeros
  return item;
 })
} 

[EDITED]

1 Like

You can also add catch to handle cases where 2 users ran it in parallel and one failed because of that.

1 Like