Nota
Modificar las propiedades del esquema de un dominio sincronizado
The following page demonstrates how to modify schema properties of a local realm. Learn how to modify schema properties of a synced realm.
When updating your object schema, you must increment the schema version and perform a migration.
Si tu actualización de esquema añade propiedades opcionales o remueve propiedades, Realm puede realizar la migración automáticamente. Solo necesitas incrementar el schemaVersion.
For more complex schema updates, you must also manually specify the migration logic in a migration function. This might include changes such as:
Agregar propiedades obligatorias que deben completarse con valores predeterminados
Combining fields
Renombrar un campo
Cambiar el tipo de un campo
Conversión de un objeto a un objeto incrustado
Tip
Bypass Migration During Development
When developing or debugging your application, you may prefer to delete the realm instead of migrating it. Use the BaseConfiguration.deleteRealmIfMigrationNeeded property to delete the database automatically when a schema mismatch requires a migration.
Nunca liberar una aplicación a producción con esta propiedad configurada en true.
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 you can include in the realm configuration. If a client application does not specify a version number, the realm defaults to version 0.
Importante
Increment Versions Monotonically
Las migraciones deben actualizar un dominio a una versión de esquema superior. El dominio genera un error si una aplicación cliente usa una versión de esquema anterior a la actual del dominio o si la versión de esquema especificada coincide con la actual del dominio, pero incluye un esquema diferente.
migración
A migration is a function that updates a realm and any objects it contains from one schema version to a newer version. Migrations allow you to change your object schemas over time to accommodate new features and refactors.
When you create a Configuration with a schema version greater than the realm's current version, Realm runs a migration function that you define. The function has access to the realm's version number and incrementally updates objects in the realm to conform to the new schema.
Realm automatically migrates certain changes, such as new and deleted properties, but does not automatically set values for new properties unless the updated object schema specifies a default value. You can define additional logic in the migration function to further customize property values.
Add a Property
To add a property to a schema, add the new property to the object's class and set a schemaVersion of the Configuration object.
Ejemplo
Un Realm que use la versión de esquema 0, que es la por defecto, tendrá un tipo de objeto Realm Person con una propiedad firstName y lastName. Decides añadir una propiedad age a la clase Person.
To migrate the realm to conform to the updated Person schema, you set the realm's schema version in the Configuration to 1. Finally, pass the configuration object to the createRealmContext() method.
class Person extends Realm.Object { static schema = { name: 'Person', properties: { _id: 'string', firstName: 'string', lastName: 'string', // add a new property, 'age' to the schema age: 'int', }, }; } const config = { schema: [Person], // Increment the 'schemaVersion', since 'age' has been added to the schema. // The initial schemaVersion is 0. schemaVersion: 2, }; // pass the configuration object with the updated 'schemaVersion' to // createRealmContext() const {RealmProvider} = createRealmContext(config);
class Person extends Realm.Object<Person> { _id!: string; firstName!: string; lastName!: string; age!: number; static schema: ObjectSchema = { name: 'Person', properties: { _id: 'string', firstName: 'string', lastName: 'string', // add a new property, 'age' to the schema age: 'int', }, }; } const config: Realm.Configuration = { schema: [Person], // Increment the 'schemaVersion', since 'age' has been added to the schema. // The initial schemaVersion is 0. schemaVersion: 2, }; // pass the configuration object with the updated 'schemaVersion' to // createRealmContext() const {RealmProvider} = createRealmContext(config);
Eliminar una propiedad
Para borrar una propiedad de un esquema, remueva la propiedad de la clase del objeto y establezca un schemaVersion del objeto Configuración. Borrar una propiedad no afectará a los objetos existentes.
Ejemplo
A realm using schema version 0, the default, has a Person object type with a lastName property. You decide to remove the property from the schema.
Para migrar el realm para que cumpla con el esquema Person actualizado, debe definir la versión del esquema del realm en 1 en el objeto Configuration. Por último, transmita el objeto de configuración al método createRealmContext().
class Person extends Realm.Object { static schema = { name: 'Person', properties: { _id: 'string', firstName: 'string', age: 'int', }, }; } const config = { schema: [Person], // Increment the 'schemaVersion', since 'lastName' has been removed from the schema. // The initial schemaVersion is 0. schemaVersion: 1, }; // pass the configuration object with the updated 'schemaVersion' to createRealmContext() const {RealmProvider} = createRealmContext(config);
class Person extends Realm.Object<Person> { _id!: string; firstName!: string; age!: number; static schema: ObjectSchema = { name: 'Person', properties: { _id: 'string', firstName: 'string', age: 'int', }, }; } const config: Realm.Configuration = { schema: [Person], // Increment the 'schemaVersion', since 'lastName' has been removed from the schema. // The initial schemaVersion is 0. schemaVersion: 1, }; // pass the configuration object with the updated 'schemaVersion' to createRealmContext() const {RealmProvider} = createRealmContext(config);
Rename a Property
Para cambiar el nombre de una propiedad de objeto, cambie el nombre de la propiedad en el esquema del objeto y luego cree una configuración de reino con una versión de esquema incrementada y una función de migración que actualice los objetos existentes para usar el nuevo nombre de propiedad.
Migrations do not allow you to directly rename a property. Instead, you can create a new property with the updated name, copy the value from the old property, and then delete the old property.
Ejemplo
Un realm que utiliza la versión del esquema 0, que es el valor por defecto, tiene un tipo de objeto Realm Person. El esquema original tenía un campo firstName y uno lastName. Luego se decide que la clase Person debe usar un campo fullName combinado y remover los campos independientes firstName y lastName.
Para migrar el realm a fin de cumplir con el esquema Person actualizado, crea un objeto Configuration y configura la versión del esquema del realm a 1, y define una función de migración que establezca el valor de fullName en función de las propiedades existentes firstName y lastName. Finalmente, pasa el objeto de configuración al método createRealmContext().
class Person extends Realm.Object { static schema = { name: 'Person', properties: { _id: 'string', // rename the 'firstName' and 'lastName' property, to 'fullName' // in the schema fullName: 'string', age: 'int', }, }; } const config = { schema: [Person], // Increment the 'schemaVersion', since 'fullName' has replaced // 'firstName' and 'lastName' in the schema. // The initial schemaVersion is 0. schemaVersion: 1, onMigration: (oldRealm, newRealm) => { // only apply this change if upgrading schemaVersion if (oldRealm.schemaVersion < 1) { const oldObjects = oldRealm.objects(Person); const newObjects = newRealm.objects(Person); // loop through all objects and set the fullName property in the // new schema for (const objectIndex in oldObjects) { const oldObject = oldObjects[objectIndex]; const newObject = newObjects[objectIndex]; newObject.fullName = `${oldObject.firstName} ${oldObject.lastName}`; } } }, }; // pass the configuration object with the updated 'schemaVersion' and // 'migration' function to createRealmContext() const {RealmProvider} = createRealmContext(config);
class Person extends Realm.Object<Person> { _id!: string; fullName!: string; age!: number; static schema: ObjectSchema = { name: 'Person', properties: { _id: 'string', // rename the 'firstName' and 'lastName' property, to 'fullName' // in the schema fullName: 'string', age: 'int', }, }; } class OldObjectModel extends Realm.Object<OldObjectModel> { _id!: string; firstName!: string; lastName!: string; age!: number; static schema: ObjectSchema = { name: 'Person', properties: { _id: 'string', firstName: 'string', lastName: 'string', }, }; } const config: Realm.Configuration = { schema: [Person], // Increment the 'schemaVersion', since 'fullName' has replaced // 'firstName' and 'lastName' in the schema. // The initial schemaVersion is 0. schemaVersion: 1, onMigration: (oldRealm: Realm, newRealm: Realm) => { // only apply this change if upgrading schemaVersion if (oldRealm.schemaVersion < 1) { const oldObjects: Realm.Results<OldObjectModel> = oldRealm.objects(OldObjectModel); const newObjects: Realm.Results<Person> = newRealm.objects(Person); // loop through all objects and set the fullName property in the // new schema for (const objectIndex in oldObjects) { const oldObject = oldObjects[objectIndex]; const newObject = newObjects[objectIndex]; newObject.fullName = `${oldObject.firstName} ${oldObject.lastName}`; } } }, }; // pass the configuration object with the updated 'schemaVersion' and // 'migration' function to createRealmContext() const {RealmProvider} = createRealmContext(config);
Importante
Realms sincronizados
Los dominios sincronizados solo admiten cambios continuos (también llamados aditivos) para garantizar que los clientes antiguos puedan sincronizarse con los nuevos. Dado que los cambios de nombre completos requieren la eliminación de la propiedad anterior, no es posible cambiar el nombre de una propiedad sincronizada sin reiniciar el cliente. En su lugar, considere agregar la propiedad renombrada sin eliminar la anterior. Como alternativa, use mapTo para almacenar datos con el nombre interno existente, pero permita que su código use un nombre diferente.
Modify a Property Type
To modify a property's type, set the property type of the field that you wish to modify to the new data type. Then, set a schemaVersion, and a migration callback function of the Configuration object.
Nota
Synchronized realms only support non-breaking changes to ensure that older clients can sync with newer clients. This means that synchronized realms do not support modifying the type of a property of a schema.
Ejemplo
A realm using schema version 0, the default, has a Person object type. The original schema had an _id with a property type of int. You later decide that the Person class's _id field should be of type ObjectId, and updates the schema.
Para migrar el realm y ajustarlo al esquema actualizado Person, crea un objeto Configuration y define la versión del esquema del realm como 1, y define una función de migración para convertir el tipo entero al tipo Object ID. Por último, pasa el objeto de configuración al método createRealmContext().
class Person extends Realm.Object { static schema = { name: 'Person', properties: { // update the data type of '_id' to be 'objectId' within the schema _id: 'objectId', firstName: 'string', lastName: 'string', }, }; } const config = { schema: [Person], // Increment the 'schemaVersion', since the property type of '_id' // has been modified. // The initial schemaVersion is 0. schemaVersion: 1, onMigration: (oldRealm, newRealm) => { if (oldRealm.schemaVersion < 1) { const oldObjects = oldRealm.objects(Person); const newObjects = newRealm.objects(Person); // loop through all objects and set the _id property // in the new schema for (const objectIndex in oldObjects) { const oldObject = oldObjects[objectIndex]; const newObject = newObjects[objectIndex]; newObject._id = new Realm.BSON.ObjectId(oldObject._id); } } }, }; // Pass the configuration object with the updated // 'schemaVersion' and 'migration' function to createRealmContext() const {RealmProvider} = createRealmContext(config);
class Person extends Realm.Object<Person> { _id!: Realm.BSON.ObjectId; firstName!: string; lastName!: string; age!: number; static schema: ObjectSchema = { name: 'Person', properties: { // Update the data type of '_id' to be 'objectId' within the schema. _id: 'objectId', firstName: 'string', lastName: 'string', }, }; } // `OldObjectModel` is only used for type injection for `oldRealm`. It is // not related to the `Person` object model. interface OldObjectModel { _id: Realm.BSON.ObjectId; firstName: string; lastName: string; age: number; } const config: Realm.Configuration = { schema: [Person], // Increment the 'schemaVersion', since the property type of '_id' // has been modified. // The initial schemaVersion is 0. schemaVersion: 1, onMigration: (oldRealm: Realm, newRealm: Realm) => { if (oldRealm.schemaVersion < 1) { const oldObjects: Realm.Results<OldObjectModel> = oldRealm.objects(Person); const newObjects: Realm.Results<Person> = newRealm.objects(Person); // Loop through all objects and set the _id property // in the new schema. for (const objectIndex in oldObjects) { const oldObject = oldObjects[objectIndex]; const newObject = newObjects[objectIndex]; newObject._id = new Realm.BSON.ObjectId(oldObject._id); } } }, }; // Pass the configuration object with the updated // 'schemaVersion' and 'migration' function to createRealmContext(). const {RealmProvider} = createRealmContext(config);