Hi,
I have created complex beforeInsert hook that is not fully behaving as I intend. The issue is slightly complicated, so I will explain the situation first.
The hook involves several queries and toInsert functions, which involve other collections, not just the collection directly associated with the hook.
There are 3 collections involved ( Client , Invoice , Tuition ).
The beforeInsert hook is associated with the Invoice collection, and follows this sequence (using async, await, try/catch blocks):
-
front end toInsert Invoice item > calls the beforeInsert hook.
-
hook queries Invoice collection > runs some functions (creates new invoice number, etc.) > assigns to new Invoice item.
-
hook then queries the Client collection > assigns relevant values to the Invoice item (client name, address, etc).
-
hook then uses various toInsert functions to add items to the Tuition collection (using values from both the Client and Invoice queries)
-
hook finally queries the Tuition collection (expecting to find return the newly inserted items which are used to calculate invoice balance). <<< this is the problem!
-
hook returns the Invoice item.
This issue is that (4.) inserts new items into the Tuition collection, then (5.) queries the Tuition collection - but the query does not return any of the newly inserted items, and the returned Invoice item does not have the correct value (balance).
If I run the Tuition query (4.) in a beforeUpdate(Invoices) hook, the query returns all the new items no problem and the returned Invoice item now has the correct value.
It is clear that items are not inserted into the Tuition collection until the entire hook has run through and returned the Invoice item, hence why the Tuition query doesn’t return the new items unless the hook has been completed…
I am running the sequence in try{await function }catch(e){} blocks, but it doesn’t make any difference.
Is there a way to force the insert to take place before the subsequent query (but the final query still take place within the same hook). Or am I trying to do something impossible?
Any advice would be greatly appreciated.
The work around I have at the moment is to run the query in a beforeUpdate query, and just arbitrarily update each item. But that is not practical!
I can post the code for the function if necessary, but I was hoping for a general “not possible” or “you need to do this instead” answer…
Many thanks in advance!
J