Customize data model identifiers
Identifiers are defined using the .identifier()
method on a model definition. Usage of the .identifier()
method is optional; when it's not present, the model will automatically have a field called id
of type ID
that is automatically generated unless manually specified.
1const schema = a.schema({2 Todo: a.model({3 content: a.string(),4 completed: a.boolean(),5 })6});
1const client = generateClient<Schema>();2
3const todo = await client.models.Todo.create({ content: 'Buy Milk', completed: false });4console.log(`New Todo created: ${todo.id}`); // New Todo created: 5DB6B4CC-CD41-49F5-9844-57C0AB506B69
If you want, you can use Amplify Data to define single-field and composite identifiers:
- Single-field identifier with a consumer-provided value (type:
id
orstring
, and must be markedrequired
) - Composite identifier with a set of consumer-provided values (type:
id
orstring
, and must be markedrequired
)
Single-field identifier
If the default id
identifier field needs to be customized, you can do so by passing the name of another field.
1const schema = a.schema({2 Todo: a.model({3 todoId: a.id().required(),4 title: a.string(),5 completed: a.boolean(),6 }).identifier(['todoId'])7});8
9const client = generateClient<Schema>();10
11const todo = await client.models.Todo.create({ todoId: 'MyUniqueTodoId', title: 'Buy Milk', completed: false });12console.log(`New Todo created: ${todo.todoId}`); // New Todo created: MyUniqueTodoId
Composite identifier
For cases where items are uniquely identified by more than a single field, you can pass an array of the field names to the identifier()
function:
1const schema = a.schema({2 StoreBranch: a.model({3 tenantId: a.id().required(),4 name: a.string().required(),5 country: a.string(),6 state: a.string(),7 city: a.string(),8 zipCode: a.string(),9 streetAddress: a.string(),10 }).identifier(['tenantId', 'name'])11});12
13const client = generateClient<Schema>();14
15const branch = await client.models.StoreBranch.get({ tenantId: '123', name: 'Downtown' }); // All identifier fields are required when retrieving an item