Schema: Lift anonymous object types
A common pattern is to have objects embedded within your document, which allows for a logical grouping of fields. For instance, a person
might have an address
which consists of many fields (street name, zip, country etc).
One way of doing this is to create an inline object for the field:
export default {
name: 'person',
title: 'Person',
type: 'object',
fields: [
{
name: 'name',
title: 'Name',
type: 'string'
},
{
name: 'address',
title: 'Address',
type: 'object',
fields: [
{name: 'street', type: 'string', title: 'Street name'},
{name: 'zip', type: 'string', title: 'Zip code'}
]
}
]
}
While this works for most cases, it can often be smart (and sometimes necessary) to "lift" this type up and define it as a global schema type.
Doing so can often lead to a more thought-out and future proof data model, since you will often rethink the fields in a global context - "how can I define this type so it can be reused for both businesses and person records?"
It can also help you reason about the same records when consuming the API from an application - perhaps you'll want to mirror the schema in TypeScript definitions or Go structs, or create a GraphQL API.
To lift a type, simply create a new type for it in the same way you would with a person type and import it into your schema:
export default {
name: 'address',
title: 'Address',
type: 'object',
fields: [
{name: 'street', type: 'string', title: 'Street name'},
{name: 'zip', type: 'string', title: 'Zip code'}
]
}
Then, in your person model, set address
as the type for the address field:
export default {
name: 'person',
title: 'Person',
type: 'object',
fields: [
{
name: 'name',
title: 'Name',
type: 'string'
},
{
name: 'address',
title: 'Address',
type: 'address'
}
]
}