Add/Modify a field in `afterChange` collection Hook

default discord avatar
2 months ago


I am trying to add/modify a field in


collection hook. Can anyone advise me how I can achieve that? I tried doing:

hooks: {
    afterChange: [
      async (data) => {

        data.doc.new_field = 'test'        // adding a new field => doesn't work
        data.doc.existing_field = 'test'   // works locally but value is not reflected in db 

This might seem as a straight forward question, but I don't find a way for it.

  • default discord avatar
    2 months ago

    @loaialsharee Does it have to be done in the afterChange hook?

    Also, I notice you're not returning the doc in the afterChange hook

  • default discord avatar
    2 months ago

    @notchr Thank you for your insight! It seems that I need to add the


    to the collection fields first to be able to reflect on both db and API from the hooks. It appears that it doesn't create a field on the fly.

    For the existing fields (like the ones attached with the image upload field once linked with Media collection by default), I guess modifying them is not possible.

  • discord user avatar
    Payload Team
    2 months ago

    - Adding fields on the fly is not possible. Payload is code first, so adding the field to your collection fields is the way to go

    - You can modify fields, but you are likely looking for a beforeChange hook, afterChange is too late, the data has already been saved in the DB

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.