Realm Object Models
Para definir un objeto Realm, derive una clase de Objeto. Los modelos que define se asignan a su propia colección en MongoDB Atlas. En este ejemplo, ambos
Dog y Person se asignarían a colecciones separadas en MongoDB Atlas.
class Dog: Object { (primaryKey: true) var _id = ObjectId() var name = "" var age = 0 } class Person: Object { (primaryKey: true) var _id = ObjectId() var name = "" }
JSON Schema
When you have a corresponding schema in Atlas App Services, Device Sync automatically converts the Realm Swift data types to BSON as it syncs to Atlas. When the client device syncs the data down from App Services via Device Sync, the SDK converts BSON back to Swift objects. If you query for these objects by accessing MongoDB Atlas data directly instead of using Device Sync to sync the data, you get the BSON data types. MongoDB Data Access does not automatically map to the Swift object equivalents.
{ "title": "Dog", "bsonType": "object", "required": [ "_id" ], "properties": { "_id": { "bsonType": "objectId" }, "name": { "bsonType": "string" }, "age": { "bsonType": "long" } } }
{ "title": "Person", "bsonType": "object", "required": [ "_id" ], "properties": { "_id": { "bsonType": "objectId" }, "name": { "bsonType": "string" } } }
Relaciones de Realm
To-One Relationship
Using the objects in the example above, consider a case where a Person can have one Dog. We can add a dog property to our Person model that is an optional link to a Dog object. To-one relationships must be optional.
class Dog: Object { (primaryKey: true) var _id = ObjectId() var name = "" var age = 0 } class Person: Object { (primaryKey: true) var _id = ObjectId() var name = "" // To-one relationship var dog: Dog? }
JSON Schema
In the App Services schema, we see the new property translates to a field dog. The field is not in the required array because it is an optional property. Its type is an objectId which links to a specific Dog object in the separate Dog collection. The objectId is the primary key of the Dog model, so it's the field that links the two objects.
{ "title": "Person", "bsonType": "object", "required": [ "_id" ], "properties": { "_id": { "bsonType": "objectId" }, "dog": { "bsonType": "objectId" }, "name": { "bsonType": "string" } } }
El esquema Dog no cambia. Al ser una relación de uno a uno, es unidireccional; Dog no tiene relación con Person.
Tip
Para obtener más información sobre las relaciones de uno a uno, consulte: Relación de uno a uno.
Relación de muchos
Usando los objetos del ejemplo anterior, considere un caso donde un Person puede tener muchos perros. Podemos agregar una propiedad dogs a nuestro modelo Person, que es una lista de Dog objetos. Si la persona no tiene perros, esta lista está vacía. A medida que la persona adquiere perros, podemos crear nuevos objetos de perro y añadirlos a la lista dogs de la persona.
class Dog: Object { (primaryKey: true) var _id = ObjectId() var name = "" var age = 0 } class Person: Object { (primaryKey: true) var _id = ObjectId() var name = "" // To-many relationship - a person can have many dogs var dogs: List<Dog> }
JSON Schema
En el esquema de los servicios de la aplicación, vemos que la nueva propiedad se traduce en un campo dogs. El tipo de este campo es un arreglo, los elementos del arreglo son de tipo objectId. Esto se debe a que definimos la llave primaria en nuestro modelo Dog como un objectId. Este campo es un arreglo de las llaves primarias de todos los objetos Dog relacionados con el objeto Person.
{ "title": "Person", "bsonType": "object", "required": [ "_id" ], "properties": { "_id": { "bsonType": "objectId" }, "name": { "bsonType": "string" }, "dogs": { "bsonType": "array", "items": { "bsonType": "objectId" } } } }
Tip
Para obtener más información sobre las relaciones de muchos, consulte: Relación de muchos.
Relación inversa
Using the objects in the example above, consider a case where the Dog object has an inverse relationship to the Person object.
class Dog: Object { (primaryKey: true) var _id = ObjectId() var name = "" var age = 0 // The backlink to the `Person` who has this `Dog`. (originProperty: "dogs") var person: LinkingObjects<Person> } class Person: Object { (primaryKey: true) var _id = ObjectId() var name = "" // To-many relationship - a person can have many dogs var dogs: List<Dog> }
JSON Schema
In the App Services schema, we see that the person property that represents the inverse relationship to a Person from our Dog model is not present. You can't directly set the value of an inverse relationship, and that relationship does not exist in Atlas. However, Realm derives and updates those relationships for you in the client application based on your Realm object model.
{ "title": "Dog", "bsonType": "object", "required": [ "_id" ], "properties": { "_id": { "bsonType": "objectId" }, "name": { "bsonType": "string" }, "age": { "bsonType": "long" } } }
Tip
For more information about inverse relationships, see: Inverse Relationship.
Embedded Object Models
Al definir un objeto incrustado con el SDK de Realm Swift, se deriva una clase de EmbeddedObject. Se puede hacer referencia a un tipo de objeto incrustado desde tipos de objeto padre de la misma manera que se define una relación:
class Person: Object { (primaryKey: true) var id = 0 var name = "" // To-many relationship - a person can have many dogs var dogs: List<Dog> // Inverse relationship - a person can be a member of many clubs (originProperty: "members") var clubs: LinkingObjects<DogClub> // Embed a single object. // Embedded object properties must be marked optional. var address: Address? convenience init(name: String, address: Address) { self.init() self.name = name self.address = address } } class DogClub: Object { var name = "" var members: List<Person> // DogClub has an array of regional office addresses. // These are embedded objects. var regionalOfficeAddresses: List<Address> convenience init(name: String, addresses: [Address]) { self.init() self.name = name self.regionalOfficeAddresses.append(objectsIn: addresses) } } class Address: EmbeddedObject { var street: String? var city: String? var country: String? var postalCode: String? }
JSON Schema
Embedded objects map to embedded documents in the parent type's schema. This behavior differs from regular Realm objects, which map to their own MongoDB collection.
{ "title": "Person", "bsonType": "object", "required": ["id"], "properties": { "id": { "bsonType": "int" }, "name": { "bsonType": "string" }, "dogs": { "bsonType": "array", "items": { "bsonType": "objectId" } }, "address": { "title": "Address", "bsonType": "object", "properties": { "street": { "bsonType": "string" }, "city": { "bsonType": "string" }, "country": { "bsonType": "string" }, "postalCode": { "bsonType": "string" } } } } }
{ "title": "DogClub", "bsonType": "object", "required": ["_id", "name", "addresses"], "properties": { "_id": "objectId", "name": { "bsonType": "string" }, "members": { "bsonType": "array", "items": { "bsonType": "objectId" } }, "addresses": { "bsonType": "array", "items": { "title": "Address", "bsonType": "object", "properties": { "street": { "bsonType": "string" }, "city": { "bsonType": "string" }, "country": { "bsonType": "string" }, "postalCode": { "bsonType": "string" } } } } } }
Create Object Models and Schemas
Para mapear entre modelos de objetos de SDK y datos BSON en Atlas, debe tener un esquema en Servicios de aplicación que coincida con su modelo de objeto de SDK. Existen varias formas de generar modelos de esquema y de objetos coincidentes:
Create object models in the client application, and generate App Services schemas from them.
Crea esquemas en App Services y genera modelos de objetos de Realm a partir de ellos.
Si está desarrollando una nueva aplicación cliente, probablemente desee iterar sobre el modelo de datos de la aplicación. Habilite el modo de desarrollo en App Services para que el backend infiera y actualice el esquema según los modelos de objetos de cliente. El modo de desarrollo no funciona con cambios importantes en el esquema, por lo que debe eliminar el esquema existente del servidor al realizar cambios importantes en el modelo de datos del SDK.
If you are developing a client application that works with data that already exists in Atlas, you can generate a schema from that data. Then, you can generate SDK object models from the server-side schema.