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
sourceAssetproperty 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
sourceAssetproperty 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.
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.tsThat makes sense and setting
nullinstead of undefined seems to do the trick. Thank you.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.