Puedes cambiar el esquema de un objeto Realm después de crearlo por primera vez. Dependiendo del tipo de cambios que realices en el esquema, estos pueden aplicarse automáticamente o requerir una actualización manual al nuevo esquema. Las actualizaciones manuales de esquema se denominan migraciones en Realm.
Puede actualizar automáticamente un esquema de objeto de Realm al agregar o eliminar una propiedad de un modelo de objeto de Realm. Para obtener más información, consulte Sección Actualizar esquema automáticamente.
You must perform a manual migration for all other schema changes. For more information, refer to the Manually Migrate Schema section.
Tip
Bypass Migration During Development
Al desarrollar o depurar su aplicación, puede que prefiera eliminar el dominio en lugar de migrarlo. Utilice LocalConfiguration.shouldDeleteIfMigrationNeeded. propiedad para eliminar la base de datos automáticamente cuando una falta de coincidencia de esquema requiere una migración.
Importante
Modify Schema Properties of a Synced Realm
El contenido de esta página solo se aplica a los dominios locales. La migración de esquemas funciona de forma diferente para dominios que utilizan Atlas Device Sync para sincronizar datos con MongoDB Atlas.Consulte la sección "Actualizar el esquema de un dominio sincronizado".
Schema Version
A schema version identifies the state of a realm schema at some point in time. Realm tracks the schema version of each realm and uses it to map the objects in each realm to the correct schema.
Schema versions are ascending integers that you can optionally include in the realm configuration when you open a realm. If a client application does not specify a version number when it opens a realm then the realm defaults to version 0.
Manual migrations must update a realm to a higher schema version. Realm throws an error if a client application opens a realm with a schema version that is lower than the realm's current version or if the specified schema version is the same as the realm's current version but includes different object schemas.
Automatically Update Schema
Realm can automatically migrate added and deleted properties. You must update the schema version when you make these changes.
Add a Property
To add a property to a schema:
Añade la nueva propiedad a la clase
RealmModeldel objeto.Set a schema version to the realm's Configuration object.
Ejemplo
A realm using schema version 1 has a Person object type with a firstName, and lastName property. The developer decides to add an age property to the _Person RealmModel class.
Para cambiar el reino para que se ajuste al Person esquema actualizado, el desarrollador establece la versión del esquema del reino 2 en.
() class _Person { late String firstName; late String lastName; late int age; }
final config = Configuration.local([Person.schema], schemaVersion: 2); final realm = Realm(config);
Delete a Property
Para borrar una propiedad de un esquema:
Remove the property from the object's
RealmModelclass.En la configuración del realm, incluye el
RealmObject.schemaregenerado e incrementa elschemaVersion.
Deleting a property does not impact existing objects.
Ejemplo
A realm using schema version 1 has a Person object type with a weight property. The developer decides to remove the property from the schema.
Para migrar el reino para Person que se ajuste al esquema actualizado, el desarrollador establece la versión del esquema del reino 2 en.
final config = Configuration.local([Person.schema], schemaVersion: 2); final realm = Realm(config);
Manually Migrate Schema
For more complex schema updates, Realm requires you to manually migrate old instances of a given object to the new schema.
When you open the realm with the updated schema, you must do the following in the realm's Configuration:
Increment the
schemaVersionproperty.Define the migration logic in a migrationCallback property of a realm's Configuration. The migration callback has the following parameters:
Las siguientes secciones explican cómo realizar diversas operaciones de migración.
Borrar un tipo de objeto Realm
To delete all objects of a type from your realm, pass a string representation of the object schema's name to Migration.deleteType().
Esto resulta útil si la versión anterior de un esquema tiene un tipo de objeto Realm, pero la nueva versión del esquema no lo tiene.
final configWithoutPerson = Configuration.local([Car.schema], schemaVersion: 2, migrationCallback: ((migration, oldSchemaVersion) { // Between v1 and v2 we removed the Person type migration.deleteType('Person'); })); final realmWithoutPerson = Realm(configWithoutPerson);
Rename a Property
Rename a schema property with Migration.renameProperty().
final configWithRenamedAge = Configuration.local([Person.schema, Car.schema], schemaVersion: 2, migrationCallback: ((migration, oldSchemaVersion) { // Between v1 and v2 we renamed the Person 'age' property to 'yearsSinceBirth' migration.renameProperty('Person', 'age', 'yearsSinceBirth'); })); final realmWithRenamedAge = Realm(configWithRenamedAge);
Other Migration Tasks
To perform other realm schema migrations, use the following properties of the Migration object in your migration callback function:
Migration.oldRealm: The realm as it existed just before the migration with the previous schema version. You must use the
oldRealm's dynamic API to access its objects because you cannot use standard type-based queries. The dynamic API lets you find Realm objects by a string representation of their class name.Migration.newRealm: The realm as it exists after the migration. By the end of the migration callback, you must migrate all data affected by the schema update from
oldRealmintonewRealm. Any data affected by the schema update that is not migrated will be lost.
To find instances of an object in an old realm in the new realm, use Migration.findInNewRealm(). To access the properties of objects from the old schema, use the RealmObjectBase.dynamic API.
final configWithChanges = Configuration.local([Person.schema, Car.schema], schemaVersion: 2, migrationCallback: ((migration, oldSchemaVersion) { // Dynamic query for all Persons in previous schema final oldPeople = migration.oldRealm.all('Person'); for (final oldPerson in oldPeople) { // Find Person instance in the updated realm final newPerson = migration.findInNewRealm<Person>(oldPerson); if (newPerson == null) { // That person must have been deleted, so nothing to do. continue; } // Use dynamic API to get properties from old schema and use in the // new schema newPerson.fullName = "${oldPerson.dynamic.get<String>("firstName")} ${oldPerson.dynamic.get<String>("lastName")}"; // convert `id` from ObjectId to String final oldId = oldPerson.dynamic.get<ObjectId>("id"); newPerson.id = oldId.toString(); } })); final realmWithChanges = Realm(configWithChanges);
Actualizar el esquema de un Realm sincronizado
Actualizar el esquema de un realm sincronizado es un proceso separado de la actualización del esquema de un realm sólo local.
Synced realms do not have schema versions and automatically migrate objects to the latest schema. Synced realms only support non-breaking schema changes.
Aprende cómo modificar las propiedades del esquema de un realm sincronizado.