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.
Importante
Increment Versions Monotonically
Migrations must update a realm to a higher schema version. Realm will throw 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.
migración
Una migración es una función que actualiza un Realm y cualquier objeto que contenga de una versión de esquema a otra más reciente. Las migraciones te ofrecen la flexibilidad de cambiar tus esquemas de objetos con el tiempo para adaptarte a nuevas funcionalidades y refactorizaciones.
Tip
Bypass Migration During Development
Al desarrollar o depurar tu aplicación, puede preferirse borrar el realm en lugar de migrarlo. Utiliza el indicador deleteRealmIfMigrationNeeded para borrar la base de datos automáticamente cuando una discrepancia de esquema requiera una migración.
Nunca publique una aplicación en producción con esta marca configurada en true.
Al abrir un dominio existente con una versión de esquema posterior a la actual, Realm ejecuta una función de migración definida por usted. Esta función tiene acceso al número de versión del dominio y actualiza incrementalmente los objetos para que se ajusten al nuevo esquema.
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.
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.
Add a Property
Para agregar una propiedad a un esquema, agregue la nueva propiedad a la clase del objeto y establezca un schemaVersion del objeto de configuración del reino.
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 class.
Para migrar el reino para Person que se ajuste al esquema actualizado, el desarrollador establece la versión del esquema del reino 2 en.
const Person = { name: 'Person', properties: { firstName: 'string', lastName: 'string', age: 'int' } }
const realm = await Realm.open({ schema: [Person], schemaVersion: 2 });
Eliminar una propiedad
Para eliminar una propiedad de un esquema, elimínela de la clase del objeto y establezca un valor en el objeto schemaVersion de configuración del dominio. Eliminar una propiedad no afecta a los objetos existentes.
Ejemplo
A realm using schema version 1 has a Dog object type with a weight property. The developer decides to remove the property from the schema.
Para migrar el reino para Dog que se ajuste al esquema actualizado, el desarrollador establece la versión del esquema del reino 2 en.
const realm = await Realm.open({ schema: [Dog], schemaVersion: 2 });
Rename a Property
To rename an object property, change the property name in the object schema and then open the realm with an incremented schema version and a migration function that updates existing objects to use the new property name.
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
A realm using schema version 1 has a Person object type. The original schema had a firstName and lastName field. The developer later decides that the Person class should use a combined fullName field and removes the separate firstName and lastName fields.
Para migrar el reino para que se ajuste al Person esquema actualizado, el desarrollador establece la versión del esquema del reino en 2 y define una función de migración para establecer el valor de en función de fullName firstName las lastName propiedades y existentes.
Realm.open({ schema: [Person], schemaVersion: 2, onMigration: (oldRealm, newRealm) => { // only apply this change if upgrading to schemaVersion 2 if (oldRealm.schemaVersion < 2) { 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}`; } } } });
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 realm's 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 1 has a Dog object type. The original schema had an _id with a property type of Object ID. The developer later decides that the Dog class's _id field should be of type string, and updates the schema.
Para migrar el reino para que se ajuste al Dog esquema actualizado, el desarrollador establece la versión del esquema del reino en 2 y define una función de migración para convertir el Object ID tipo en un string tipo.
const realm = await Realm.open({ schema: [Dog], schemaVersion: 2, onMigration: (oldRealm, newRealm) => { if(oldRealm.schemaVersion < 2){ const oldObjects = oldRealm.objects('Dog'); const newObjects = newRealm.objects('Dog'); // 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 = oldObject._id.toHexString(); } } }, });