Lesson
3
Changing a field name
Rename fields by first deprecating existing ones and marking them read only
Log in to mark your progress for each Lesson and Task
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 eventType: 'in-person'
in the JSON data. Let’s pretend that you have gotten 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. 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, format
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 also 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 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.
Add the new
format
field in the “fields” array in eventType.ts
schemaTypes/eventType.ts
defineField({ name: 'format', type: 'string', title: 'Event format', 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.
Deprecate the “Event type” field with a reason and set it as “read-only.”
schemaTypes/eventType.ts
defineField({ name: 'eventType', type: 'string', title: 'Event type', 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:
You have 2 uncompleted tasks in this lesson
0 of 2