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
tyredocument 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.idto 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
tyreSizebut 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
tyrewith previously created
tyreSizewhile creating it?
Update document field while its creating (afterChange hook, "create" operation)
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.
Thank you for answering, im was close after a few more hours trying. For me it will fix the problem and no
tyreSizewill be created if there is already
tyreSizewith same parameters.