Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

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

default discord avatar
pachachicha2 years ago
2

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

tyre

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

tyreSize.id

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 = previouslyCreatedSize.docs[0].id;
}
else.....


It find correct

tyreSize

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



payload.update(
current tyre with new data
)

but its crashing the server.


So is there any possibility to update my

tyre

with previously created

tyreSize

while creating it?



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

  • discord user avatar
    jarrod_not_jared
    2 years ago

    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.

  • default discord avatar
    pachachicha2 years ago

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

    tyreSize

    will be created if there is already

    tyreSize

    with same parameters.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.