Generating 'child' documents on creation of a parent

default discord avatar
tompatrick
8 months ago
2

I'm writing an app that handle events, and I want to generate child events based somewhat on the data in the parent when a new entry is saved.



Ideally I would reference the parents to the child, so we have a relationship and know which child belongs to which parent .



Am I right in thinking the

afterChange

collection hook is the right place for this? Or is there a better option.



If I call payload.create within the hook isn't it going to run the hook again, on every creation of a child?



I can put a guard in place to simply return if theres no parent entry, but still going to be pretty intensive.



Is there a way to prevent subsequent runs of the hook whilst this function runs.

  • default discord avatar
    Tinouti
    8 months ago
    Is there a way to prevent subsequent runs of the hook whilst this function runs.

    Could you elaborate on what you mean by that?



    Because the solution you suggested (ie: checking whether the doc has a parent or not in that

    afterChange

    function) seems like the way to go if all you need is to do is create children on the parent's save but prevent it from running subsequently on these children you're creating. 🤷‍♂️



    eg:


    - creates new item A


    -

    afterChange

    triggers for item A,

    parent

    field is empty, generate children B, C, D with the parent field set to item A


    -

    afterChange

    triggers for items B, C, and D, but

    parent

    field is provided, so nothing happens

  • default discord avatar
    tompatrick
    8 months ago

    Thanks @Tinouti. Haha, Yeah I wrote this late last night and I think my brain was cooked!! 🤣. Re-reading it today, all makes perfect sense. Thanks for the sense check.

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.