Hi,
I have a SiteUsers collection that has an email, roles and a data relationship field. Upon creating a user, I'd like to create another entry in either Organizations or Candidates collection with the email from the SiteUsers collection and update the data field with the newly created profile.
I achieved part 1 of this by using the payload.create() function.
However part 2 is where I'd like to update the data relationship field to include the ID of the created item.
import type { AfterChangeHook } from 'payload/dist/collections/config/types'
export const createProfileAfterCreate: AfterChangeHook = async ({
doc,
req,
req: { payload, body = {}, res },
operation,
}) => {
if (operation === 'create' && doc.id) {
const { email, role } = body
// Create a profile for the user
const profile = await payload.create({
collection: role,
data: {
email: email,
}
})
if (profile) {
console.log('doc', doc) // works
console.log('profile', profile) // works
// Assign the profile to the user - not working
await payload.update({
collection: 'site-users',
id: doc.id,
data: {
data: {
value: profile.id,
relationTo: role
}
},
depth: 0
})
}
}
return doc
}
I logged the doc and profile (see screenshots) and I get both the IDs of the SiteUsers collection item and the Organizations/Candidates collection item. But then I get an error
ERROR (payload): NotFound: The requested resource was not found.
I followed the official documentation and the examples and I'm not sure what I'm missing.
Weirdly enough, I don't get the error when I use where: { id: doc.id }, instead of id: doc.id,. Then the user is created, their profile in Organizations/Candidates is also created, BUT the relationship is not updated.
Thank you in advance for your help. 🙂