Auto assign ID to a new item

I created my own item’s ID field to use it on my web site, instead of Wix complicated id. I activated a beforeInsert hook for my collection, and it works fine with a simple code, like this one, which assigns “5” value to the field:

mport wixData from 'wix-data';

export function Properties_beforeInsert(item, context) {
   item.postNumber = 2 + 3;
   return item;
 }

Now I need to make a bit tricky formula, like { id value = total number of items in a collection + 1 }. I added a query functon but it’s not working - no value is put in a field. Here is my code that doesn’t work:

export function Properties_beforeInsert(item, context) {

 wixData.query("Properties")
 .find()
 .then( (results) => {
  item.postNum = results.totalCount + 1;
  });
  
 return item;
}

I’m pretty new to code, so can anyone help with this part?

Just create a function like this:

async function getLastOrderNumber() {
    let lastOrderNumber
    const queryLastOrderNumber = await wixData
        .query("Properties")
        .limit(1)
        .descending("orderNumber")
        .find()

    queryLastOrderNumber.items.length < 1
        ? (lastOrderNumber = 1)
        : (lastOrderNumber = queryLastOrderNumber.items[0].orderNumber + 1)
    console.log(lastOrderNumber)
    return lastOrderNumber
}

After a few hours of experimenting with syntax it finally works. Thank you!

Nice!

For those who may need a full solution here is the hook part that I used.

export async function Properties_beforeInsert(item, context) {    
      var newId = await getLastOrderNumber();  
      item.postNumber = newId;
  return item;
}