Like what we’re doing? Star us on GitHub!

Update document field while its creating (afterChange hook, "create" operation)

last month

I need to update field in afterChange hook in "create" operation.

There is 2 documents, 1 relates to another, like this.

const Tyres: CollectionConfig = {
fields: [
      name: "tyreSize",
      type: "relationship",
      relationTo: 'tyreSizes',
      hasMany: false,

And i wanted when im creating a new


document to checks whether there is alredy created *tyreSize * with those same parameters (so why u've used afterChange "create" operation). If same *tyreSize * is created before then i should link it via

to tyre itself, but how can i do it? because im tried

const previouslyCreatedSize = await payload.find({
            collection: tyreSizesCollection,
            where: {
              width: { equals: 100 },
              height: { equals: 50 },
              diskDiameter: { equals: 25 },
if(its created){
 args.doc.tyreSize =[0].id;

It find correct


but wont link it to tyre. I've tried to

current tyre with new data

but its crashing the server.

So is there any possibility to update my


with previously created


while creating it?

Update document field while its creating (afterChange hook, "create" operation)

  • Jarrod
    Payload Team
    last month

    On the tyreSize collection you could make a text field that has

    unique: true

    . Then with a beforeValidate hook (on operation === create) you can use the submitted data to generate the value for your unique field.

    That will solve the "no duplication" issue, but that will not solve the auto-selection you are looking for.

  • Daniq
    last month

    Thank you for answering, im was close after a few more hours trying. For me it will fix the problem and no


    will be created if there is already


    with same parameters.

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More