Changes in collection's beforeOperation hook not available in afterChange hook.

default discord avatar
KasparTrlast year
3

I'm stripping some data from the docs in the beforeOperation and/or beforeChange hooks. Nevertheless when the afterChange hooks is triggered, the data that was stripped is reappearing as if the before hooks never happened.



Is it possible to alter the collection item programmatically inside any of the before hooks and have that change propagate to the database, and consequently, keep the state in the afterChange hook also?



For example, in my beforeChange hook, I remove the

sourceAsset

property from the doc.



const assetBeforeChangeHookConfigureField: CollectionBeforeChangeHook = async ({
    data, // incoming data to update or create with
    req, // full express request
    operation, // name of the operation ie. 'create', 'update'
    originalDoc, // original document
}) => {

    data.sourceAsset = undefined
    return data; // Return data to either create or update a document with
}

export default assetBeforeChangeHookConfigureField;


Inside my afterChange hook, the

sourceAsset

property is defined again as the before hook never happened.



const assetAfterChangePublishAsset: CollectionAfterChangeHook = async ({
  doc, // full document data
  req, // full express request
  previousDoc, // document data before updating the collection
  operation, // name of the operation ie. 'create', 'update'
}) => {
  console.log("assetAfterChangePublishAsset | doc: ", doc) // doc.sourceAsset is defined.
  return doc;
}


I tried to use both beforeOperation and beforeChange hooks but the behavior is the same. Am I misunderstanding the hooks expected behavior?


Thanks.

  • default discord avatar
    jarrod69420last year

    You can pass null instead of undefined. When partial data is submitted payload checks to see if a field is defined on the existing data but is missing/undefined on the incoming data. If true then existing data is kept and merged in with the rest of the data. But if you set the value to null then payload will store that value.



    You can see the code responsible for this on line 60 here

    https://github.com/payloadcms/payload/blob/master/src/fields/hooks/beforeChange/promise.ts
  • default discord avatar
    KasparTrlast year

    That makes sense and setting

    null

    instead of undefined seems to do the trick. Thank you.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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