#Set collection ID manually

6 messages · Page 1 of 1 (latest)

weak bluff
#

Is it possible to set a collection ID manually when using the local API e.g.

await payload.create({
  collection: Post.slug,
  data: {
    id: '66a162e91d86648e1303e0d2',
    title: 'Test Post'
  },
});

When running the above a unique ID is created for that collection when I want to use this above id instead.

Note: the usage for this is for local testing and I do not intend ever performing this action in production for the obvious reasons.

snow oreBOT
weak bluff
#

Worked it out, I just needed to set _id on create.

snow oreBOT
lean grove
main comet
#

@lean grove We do this on multiple collections with a CollectionBeforeValidateHook which looks something like:

  operation,
  data,
  req,
}): Promise<void> => {
  if (operation === "create") {
    data._id = `customId`;
  }
};```

If you want to provide a custom ID when creating a collection record with the localAPI you could use req.context:

Local API  call:
```payload.create({
    collection: Collection.slug,
    data: {
      field1: val1,
      field2: val2
    },
    context: {
      customId: "customID"
    }
})```
CollectionBeforeValidateHook:
```const createAccountRecordId: CollectionBeforeValidateHook = async ({
  operation,
  data,
  req,
}): Promise<void> => {
  if (operation === "create" && req.context?.customId) {
    data._id = req.context.customId;
  }
};```