Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Datos del modelo

Change an Object Model - Kotlin SDK

Nota

Modify Schema Properties of a Synced Realm

The following page demonstrates how to modify schema properties of a local realm. Learn how to modify schema properties of a synced realm.

You can make changes to your object schema after you create your Realm object model. Depending on the type of changes you make to the schema, the changes can be automatically applied or require a manual update to the new schema.

  • Realm will automatically update a Realm object schema when you add or delete a property from a Realm object model. You only need to update the schema version.

  • For all other schema changes, you must manually migrate old instances of a given object to the new schema.

Tip

Bypass Migration During Development

Cuando desarrolles o depures tu aplicación, puedes preferir borrar el realm en lugar de migrarlo. Utiliza el flag deleteRealmIfMigrationNeeded para borrar la base de datos automáticamente cuando una incompatibilidad de esquema requiera una migración.

Never release an app to production with this flag set to true.

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.

Schema updates are called migrations in Realm. A migration updates a realm and any objects it contains from one schema version to a newer version.

Cada vez que se abre un Realm existente con una versión de esquema superior a la versión actual del Realm, se puede proporcionar una función de migración que defina cualquier lógica adicional necesaria para la actualización del esquema. Por ejemplo:

  • Setting property values

  • Combinación o división de campos

  • Renombrar un campo

  • Cambiar el tipo de un campo

La función tiene acceso al número de versión del Realm y actualiza de forma incremental los objetos en el Realm para adaptarlos al nuevo esquema.

Una migración local es una migración para un reino que no se sincroniza automáticamente con otro reino.

Nota

To modify schema properties of a synced realm, refer to Update a Data Model in the Atlas Device Sync documentation.

Si tu actualización de esquema agrega o elimina propiedades, Realm puede realizar la migración automáticamente. Solo necesitas incrementar el schemaVersion.

To add a property to a schema:

  1. Add the new property to the RealmObject definition.

  2. Establece la versión de esquema a través del constructor RealmConfiguration.

Realm automatically sets values for new properties if the updated object schema specifies a default value. If the updated object schema does not specify a default value, you must manually set values for the new property through a migration function.

Ejemplo

Un realm que utiliza la versión de esquema 1 tiene un tipo de objeto Realm Person con las propiedades nombre, apellido y edad:

// Realm schema version 1
class Person : RealmObject {
var firstName: String = ""
var lastName: String = ""
var age: Int = 0
}

The developer adds an email field to the Person class:

// Realm schema version 2
class Person : RealmObject {
var firstName: String = ""
var lastName: String = ""
var age: Int = 0
var email: String? = null
}

Para cambiar el realm y adaptarlo al esquema Person actualizado, el desarrollador establece la versión del esquema del realm en 2:

val config = RealmConfiguration.Builder(
schema = setOf(Person::class)
)
.schemaVersion(2) // Sets the new schema version to 2
.build()
val realm = Realm.open(config)

Para borrar una propiedad de un esquema:

  1. Remove the property from the object's class.

  2. Establece la versión de esquema a través del constructor RealmConfiguration.

Deleting a property will not impact existing objects.

Ejemplo

A realm using schema version 2 has a Person object type with first name, last name, age, and email properties:

// Realm schema version 2
class Person : RealmObject {
var firstName: String = ""
var lastName: String = ""
var age: Int = 0
var email: String? = null
}

El desarrollador elimina el campo age de la clase Person:

// Realm schema version 3
class Person : RealmObject {
var firstName: String = ""
var lastName: String = ""
// var age: Int = 0
var email: String? = null
}

Para cambiar el realm y adaptarlo al esquema Person actualizado, el desarrollador establece la versión del esquema del realm en 3:

val config = RealmConfiguration.Builder(
schema = setOf(Person::class)
)
.schemaVersion(3) // Sets the new schema version to 3
.build()
val realm = Realm.open(config)

For more complex schema updates, Realm requires you to manually migrate old instances of a given object to the new schema.

Cuando se abre el realm con el esquema actualizado, es necesario hacer lo siguiente en el RealmConfiguration:

  • Increment the schemaVersion property.

  • Define the migration logic using the migrationContext.

Para modificar una propiedad de objeto (por ejemplo, renombrar, fusionar, dividir o cambiar el tipo de propiedad):

  1. Change the property or properties in the object schema.

  2. Open the realm with an incremented schema version and a migration function that maps the existing objects to use the new properties.

In the following example, the schema is updated to change a property type, merge two properties into a new property, and rename an existing property:

// Realm schema version 1 (oldObject)
class Person : RealmObject {
var _id: ObjectId = ObjectId()
var firstName: String = ""
var lastName: String = ""
var age: Int = 0
}
// Realm schema version 2 (newObject)
class Person : RealmObject {
var _id: String = "" // change property type
var fullName: String = "" // merge firstName and lastName properties
var yearsSinceBirth: Int = 0 // rename property
}

Then, the migration function defines the migration logic to map data between the modified properties in the old object schema and the new object schema:

// Use the configuration builder to open the realm with the newer schema version
// and define the migration logic between your old and new realm objects
val config = RealmConfiguration.Builder(
schema = setOf(Person::class)
)
.schemaVersion(2) // Set the new schema version to 2
.migration(AutomaticSchemaMigration {
it.enumerate(className = "Person") { oldObject: DynamicRealmObject, newObject: DynamicMutableRealmObject? ->
newObject?.run {
// Change property type
set(
"_id",
oldObject.getValue<ObjectId>(fieldName = "_id").toString()
)
// Merge properties
set(
"fullName",
"${oldObject.getValue<String>(fieldName = "firstName")} ${oldObject.getValue<String>(fieldName = "lastName")}"
)
// Rename property
set(
"yearsSinceBirth",
oldObject.getValue<String>(fieldName = "age")
)
}
}
})
.build()
val realm = Realm.open(config)

Nota

Si tu actualización de esquema incluye convertir un RealmObject en un EmbeddedRealmObject, la función de migración debe garantizar que el objeto incrustado tenga exactamente un objeto padre vinculado a él. Los objetos incrustados no pueden existir independientemente de un objeto padre.

To perform other realm schema migrations, use the following properties of the AutomaticSchemaMigration.MigrationContext interface:

  • oldRealm: El dominio tal como existía antes de la migración con la versión anterior del esquema. La API dinámica permite encontrar objetos de dominio mediante una cadena que representa su nombre de clase.

  • newRealm: The realm as it exists after the migration using the new schema version.

Any objects obtained from oldRealm and newRealm are valid only in the scope of the migration function.

By the end of the migration, you must migrate all data affected by the schema update from the old realm to the new realm. Any data affected by the schema update that is not migrated will be lost.

val config = RealmConfiguration.Builder(
schema = setOf(Person::class)
)
.schemaVersion(2)
.migration(AutomaticSchemaMigration { migrationContext ->
val oldRealm = migrationContext.oldRealm // old realm using the previous schema
val newRealm = migrationContext.newRealm // new realm using the new schema
// Dynamic query for all Persons in old realm
val oldPersons = oldRealm.query(className = "Person").find()
for (oldPerson in oldPersons) {
// Get properties from old realm
val firstName: String = oldPerson.getValue(
propertyName = "firstName", String::class
)
// Get objects from old realm as dynamic realm objects
val pet: DynamicRealmObject? = oldPerson.getObject(
propertyName = "pets"
)
}
// Get migrated objects from the new realm as mutable objects
val oldPerson: DynamicMutableRealmObject? =
newRealm.findLatest(oldPersons[0])
oldPerson?.let {
it.set("fullName", "Crow T. Robot")
}
// Create an object in the new realm and set property values
val newPerson = newRealm.copyToRealm(
DynamicMutableRealmObject.create(
type = "Person",
mapOf(
"_id" to "123456",
"fullName" to "Tom Servo",
"yearsSinceBirth" to 33,
)
)
)
})
.build()
val realm = Realm.open(config)

Volver

Datos geoespaciales

En esta página