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.
Does it have to be done in the afterChange hook?
Also, I notice you're not returning the doc in the afterChange hook
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.
- 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
Star
Discord
online
Get dedicated engineering support directly from the Payload team.