Add/Modify a field in `afterChange` collection Hook

default discord avatar
loaialsharee
2 months ago
3

Hello,



I am trying to add/modify a field in

afterChange

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 
        
        console.log(data);
      },
    ],
  },

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

  • default discord avatar
    notchr
    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
    loaialsharee
    2 months ago

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

    new_field

    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
    jarrod_not_jared
    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!

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.