Changing a field name

Open an event document. There you will find the “Event Type” field that describes if the event is “In-person” or “Virtual.” When you go to the “Inspect” menu (ctrl+opt+i/ctrl+alt+i
), you see that it’s encoded
{ // ...other fields eventType: "in-person"}
Let’s pretend that you have received feedback from your developer colleagues that it’s a bit confusing to have both a document type called event
and a field type called eventType
(they're correct by the way, who modeled this schema?)
When implementing this data in an application, you also get a somewhat inelegant pattern: event.eventType
.
Naming is hard.
We want to change this field to be called “Event Format” instead, that is a format
attribute in the JSON data so that you can get the value with event.format
where this field content is used.
Now, you will not only change this field as data for developers, but you are changing it for content creators as well. Usually, if it’s early in the project, and there aren’t a lot of documents yet, you can get away with just changing the name
property of the field and manually backfilling the content.
But let’s pretend that this is a more mature project, where you have an application in production that consumes and depends on this data, and you (or someone on your team) don’t want to spend time manually going through every document to copy-paste content between the old and the new field.
In this case, changing the field name requires the following steps:
- Adding a new field with the new name
- Deprecating the old field
- Adapting a query to support the new field name and fallback on the old
- Create a content migration to move the content
Begin with adding the new field; you can copy-paste the eventFormat
field definition, and change the name.
event
document schema type to include the new format
fielddefineField({ name: 'format', type: 'string', options: { list: ['in-person', 'virtual'], layout: 'radio', },}),
You should now have two identical fields with different names and labels:
Now, you can deprecate the “Event type” field and add a guide for the content creator. You can also set it to “read-only” to prevent content creators from using it.
eventType
field to include config for deprecated
and set to readOnly
defineField({ name: 'eventType', type: 'string', deprecated: { reason: 'Use the "Event format" field instead.' }, readOnly: true, options: { list: ['in-person', 'virtual'], layout: 'radio', },}),
Save the change and confirm that the document form now looks like this:
This prevents authors from making any further changes to this field in the Studio, or any new documents with this value.
Let's update our front end to consume the new field, once it has values.