I have a list of n items that need to be inserted into my database. When an item is inserted I have to give it the next boxNumber available by adding 1 to the previously saved result. The problem is that Wix does not seem to be completing the write before resolving the promise or await as I often get the same boxnumber result for the next insert. My code is below
To insert item, I loop through them and run
result = await wixData.insert('Items', item);
return result;
My insert hook is as follows:
export function Items_beforeInsert(item, context) {
let nextNum;
return wixData.query("Items")
.limit(1)
.descending('boxNumber')
.find()
.then((results) => {
if (results.length === 0) {
let initialBoxNumber = 5000;
item.boxNumber = initialBoxNumber; //Start if collectionn empty
item.title = initialBoxNumber.toString();
}
else {
const lastItemInCollection = results.items[0];
nextNum = lastItemInCollection.boxNumber + 1;
item.boxNumber = nextNum;
item.title = nextNum.toString();
}
console.log(item.boxNumber);
return item;
})
.catch(errorHandler);
}
The problem is probably in the looping or the async function that you haven't posted here.
Anyway you can use a bulkInsert instead of many single inserts.
to do that you can add to your itemsToSave array a key tempIndx which its value is equal to it's array index +1;
then run a bulk insert and on the backend:
export function Items_beforeInsert(item, context) { return wixData.query("Items") .descending("boxNumber") .limit(1) .find() .then((results) => { if(typeof item.tempIndx === "undefined"){ item.boxNumber = results.items[0].boxNumber + 1; }else { item.boxNumber = results.items[0].boxNumber + item.tempIndx; delete item.tempIndx; } return item; }) }