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

Relaciones y objetos incrustados - SDK de Node.js

A to-one relationship means that an object is related to no more than one other object in an object schema. To define a to-one relationship, specify the property type as the related Realm object type.

Ejemplo

Una aplicación podría utilizar los siguientes esquemas de objetos para indicar que un Manufacturer puede hacer un solo Car:

class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// A manufacturer that may have one car
car: "Car?",
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
},
};
}
class Manufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
car?: Car;
static schema: ObjectSchema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// A manufacturer that may have one car
car: "Car?",
},
};
}
class Car extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
static schema: ObjectSchema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
},
};
}

Una relación de varios objetos significa que un objeto está relacionado de una manera específica con varios objetos. Para definir una relación de varios objetos, especifique una propiedad cuyo tipo sea una lista o matriz del tipo de objeto Realm relacionado en su esquemade objetos.

Ejemplo

An application could use the following object schemas to indicate that a Manufacturer may make many Car models:

class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// A manufacturer that may have many cars
cars: "Car[]",
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
},
};
}
class Manufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
cars!: Realm.List<Car>;
static schema: ObjectSchema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// A manufacturer that may have many cars
cars: "Car[]",
},
};
}
class Car extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
static schema: ObjectSchema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
},
};
}

An inverse relationship links an object back to any other objects that refer to it in a defined to-one or to-many relationship. Relationship definitions are unidirectional by default. You must explicitly define a property in the object's model as an inverse relationship.

For example, the to-many relationship "Manufacturer has many Cars" does not automatically create the inverse relationship "Car belongs to Manufacturer". If you don't specify the inverse relationship in the object model, you need to run a separate query to look up the manufacturer who makes a car.

Para definir una relación inversa, define una propiedad linkingObjects en tu modelo de objeto. linkingObjects especifica el tipo de objeto Realm y el nombre de la propiedad de la relación que invierte.

You cannot manually set the value of an inverse relationship property. Realm automatically updates implicit relationships whenever you add or remove a related object.

Ejemplo

Una aplicación podría utilizar los siguientes esquemas de objetos para indicar:

  1. Una Manufacturer puede crear muchos modelos Car.

  2. Each Car should automatically link back to the Manufacturer who makes it.

La propiedad cars del objeto Manufacturer se define como una relación de muchos con un Lista de Car objetos. Contiene todos los coches de un fabricante determinado.

La propiedad manufacturer del objeto Car invierte esta relación. La propiedad manufacturer se actualiza automáticamente para hacer referencia a cualquier objeto Manufacturer que contenga el Car en su propiedad cars.

class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// A manufacturer that may have many cars
cars: "Car[]",
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
manufacturer: {
type: "linkingObjects",
objectType: "Manufacturer",
property: "cars",
},
},
};
}
class Manufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
cars!: Realm.List<Car>;
static schema: ObjectSchema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// A manufacturer that may have many cars
cars: "Car[]",
},
};
}
class Car extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
manufacturer!: Realm.Collection<Manufacturer>;
static schema: ObjectSchema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
manufacturer: {
type: "linkingObjects",
objectType: "Manufacturer",
property: "cars",
},
},
};
}

Puedes recuperar dinámicamente un objeto con una relación inversa sin definir un tipo de linkingObjects en su esquema. Remueve el tipo linkingObjects de tu esquema, para que tus esquemas se parezcan a una relación estándar de uno a muchos. Cuando necesite recuperar el objeto vinculado, llame a Realm.Object.linkingObjects() query.

Ejemplo

In the following continuation from the inverse relationship example, we have removed the manufacturer field with type 'linkingObjects' from the Car schema. An application developer creates several manufacturers and car objects, and the application pushes the newly-created cars into a manufacturer's cars field.

Para encontrar el fabricante que hace un objeto de automóvil específico, llama a .linkingObjects() y pasa el nombre de la clase "Manufacturer" y el campo "cars" como parámetros.

The .linkingObjects() method returns a Results collection of objects whose property inverts the relationship. In this example, only one manufacturer makes the Sentra car model, so we can expect that manufacturer to be named Nissan.

const carObjects = realm.objects(Car);
// Get the Manufacturer who makes the Car
const linkedManufacturer = carObjects[0].linkingObjects(
"Manufacturer",
"cars"
)[0];
expect(linkedManufacturer.name).toBe("Nissan");
const carObjects = realm.objects<Car>(Car);
// Get the Manufacturer who makes the Car
const linkedManufacturer: Manufacturer =
carObjects[0].linkingObjects<Manufacturer>("Manufacturer", "cars")[0];
expect(linkedManufacturer.name).toBe("Nissan");

Un objeto incrustado es un tipo especial de objeto Realm que modela datos complejos. También se asemejan más naturalmente al modelo orientado a documentos de MongoDB. Los objetos incrustados son similares a las relaciones, pero ofrecen restricciones adicionales.

Realm trata cada objeto incrustado como un dato anidado dentro de un objeto principal. Un objeto incrustado hereda el ciclo de vida de su objeto principal. No puede existir como un objeto Realm independiente. Esto significa que los objetos incrustados no pueden tener una llave primaria. Realm también borra automáticamente los objetos incrustados si se borra su objeto principal.

Tip

Embedded object types are reusable and composable

You can use the same embedded object type in multiple parent object types. You can also embed objects inside of other embedded objects. You can even recursively reference an embedded object type as an optional property in its own definition.

To specify that a Realm object model defines an embedded object, set embedded to true. Reference an embedded object type from parent object types as you would define a relationship:

class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
cars: "Car[]",
// Embed an array of objects
warranties: "Warranty[]",
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
// Embed one object
warranty: "Warranty?",
},
};
}
class Warranty extends Realm.Object {
static schema = {
name: "Warranty",
embedded: true,
properties: {
name: "string",
termLength: "int",
cost: "int",
},
};
}
class Manufacturer extends Realm.Object {
_id!: BSON.ObjectId;
name!: string;
cars!: Realm.List<Car>;
warranties!: Realm.List<Warranty>;
static schema: ObjectSchema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
cars: "Car[]",
// Embed an array of objects
warranties: "Warranty[]",
},
};
}
class Car extends Realm.Object {
_id!: BSON.ObjectId;
model!: string;
miles?: number;
warranty?: Warranty;
static schema: ObjectSchema = {
name: "Car",
properties: {
_id: "objectId",
model: "string",
miles: "int?",
// Embed one object
warranty: "Warranty?",
},
};
}
class Warranty extends Realm.Object {
name!: string;
termLength!: number;
cost!: number;
static schema: ObjectSchema = {
name: "Warranty",
embedded: true,
properties: {
name: "string",
termLength: "int",
cost: "int",
},
};
}

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": "Contact",
"bsonType": "object",
"required": ["_id"],
"properties": {
"_id": { "bsonType": "objectId" },
"name": { "bsonType": "string" },
"address": {
"title": "Address",
"bsonType": "object",
"properties": {
"street": { "bsonType": "string" },
"city": { "bsonType": "string" },
"country": { "bsonType": "string" },
"postalCode": { "bsonType": "string" }
}
}
}
}
{
"title": "Business",
"bsonType": "object",
"required": ["_id", "name"],
"properties": {
"_id": { "bsonType": "objectId" },
"name": { "bsonType": "string" },
"addresses": {
"bsonType": "array",
"items": {
"title": "Address",
"bsonType": "object",
"properties": {
"street": { "bsonType": "string" },
"city": { "bsonType": "string" },
"country": { "bsonType": "string" },
"postalCode": { "bsonType": "string" }
}
}
}
}
}

Volver

Define un modelo de objeto

En esta página