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

default discord avatar
4 weeks ago

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


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


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?


  • discord user avatar
    Payload Team
    4 weeks ago

    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
  • default discord avatar
    4 weeks ago

    That makes sense and setting


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

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


Connect with the Payload Community on Discord



Can't find what you're looking for?

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