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

Define a Realm Object Model - Node.js SDK

Para definir un tipo de objeto Realm, cree un objeto de esquema que especifique el tipo name y properties. El nombre del tipo debe ser único entre los tipos de objeto de un dominio. Para obtener más información sobre cómo definir propiedades específicas, consulte Definir propiedades de objeto.

You can define your schemas with JavaScript classes (like most of the examples on this page), but you can also define them as JavaScript objects.

const Car = {
name: "Car",
properties: {
_id: "objectId",
make: "string",
model: "string",
miles: "int?",
},
};

Puedes definir tipos de objetos Realm con clases de JavaScript. Para utilizar una clase como un tipo de objeto Realm, definir el esquema de objeto en la propiedad estática schema.

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", default: () => new Realm.BSON.ObjectId() },
make: "string",
model: "string",
miles: "int?",
},
primaryKey: "_id",
};
}

Nota

Class names are limited to a maximum of 57 UTF-8 characters.

Pase la clase a la propiedad de esquema del objeto Realm.Configuration al abrir un dominio. De esta forma, podrá leer y escribir datos con normalidad.

const realm = await Realm.open({
path: "myrealm",
schema: [Car],
});
let car1;
realm.write(() => {
car1 = realm.create(Car, {
make: "Nissan",
model: "Sentra",
miles: 1000,
});
});

Cada propiedad de un objeto Realm tiene un tipo de dato claramente definido. El tipo de una propiedad puede ser un tipo de dato primitivo o un tipo de objeto definido en el mismo reino. El tipo también especifica si la propiedad contiene un único valor o una lista de valores.

Realm supports the following primitive data types:

To specify that a field contains a list of a primitive value type, append [] to the type name.

Para definir una propiedad para un tipo de objeto Realm, crea un par clave-valor que represente el nombre y el tipo de dato de la propiedad en el campo properties.

El siguiente esquema define un tipo Car que tiene estas propiedades: _id make, model y miles.

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", default: () => new Realm.BSON.ObjectId() },
make: "string",
model: "string",
miles: "int?",
},
primaryKey: "_id",
};
}

Para marcar una propiedad como opcional, agregue un signo de interrogación ? a su tipo.

The following Car schema defines an optional miles property of type int.

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", default: () => new Realm.BSON.ObjectId() },
make: "string",
model: "string",
miles: "int?",
},
primaryKey: "_id",
};
}

To specify a property as an object type's primary key, set the schema's primaryKey field to the property name.

Nota

Una clave principal es una propiedad que identifica de forma única a un objeto. Realm indexa automáticamente las propiedades de clave principal, lo que permite leer y modificar objetos de forma eficiente según su clave principal.

If an object type has a primary key, then all objects of that type must include the primary key property with a value that is unique among objects of the same type in a realm. An object type may have at most one primary key. You cannot change the primary key property for an object type after any object of that type is added to a realm and you cannot modify an object's primary key value.

The following Car object schema specifies the _id property as its primary key.

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", default: () => new Realm.BSON.ObjectId() },
make: "string",
model: "string",
miles: "int?",
},
primaryKey: "_id",
};
}

Realm supports indexing for string, integer, boolean, Date, UUID, and ObjectId properties. To define an index for a given property, set indexed to true.

Nota

Un índice aumenta significativamente la velocidad de ciertas operaciones de lectura a costa de tiempos de escritura ligeramente más lentos y de un mayor uso de almacenamiento y memoria. Realm almacena índices en disco, lo que hace que sus archivos de Realm sean más grandes. Cada entrada de índice consta de un mínimo de 12 bytes. El ordenamiento de las entradas de índice admite coincidencias exactas eficientes y operaciones de query basadas en rangos.

It's best to only add indexes when optimizing the read performance for specific situations.

El siguiente esquema de objeto Car define un índice en la propiedad _id.

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", indexed: true },
make: "string",
model_name: { type: "string", mapTo: "modelName" },
miles: { type: "int", default: 0 },
},
primaryKey: "_id",
};
}

Además de los índices estándar, Realm también admite índices de búsqueda de texto completo (FTS) en propiedades de cadena. Si bien se puede consultar un campo de cadena con o sin un índice estándar, un índice FTS permite buscar múltiples palabras y frases, excluyendo otras.

For more information on querying FTS indexes, see Filter with Full-Text Search.

To create an FTS index, set the indexed type to 'full-text'. This enables full-text queries on the property. In the following example, we set the indexed type for the name property to 'full-text':

class Book extends Realm.Object<Book> {
name!: string;
price?: number;
static schema: ObjectSchema = {
name: "Book",
properties: {
name: { type: "string", indexed: "full-text" },
price: "int?",
},
};
}

To define a default value, set the value of the property to an object with a type field and a default field.

El siguiente esquema de objeto Car especifica un valor predeterminado de 0 para la propiedad miles:

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", indexed: true },
make: "string",
model_name: { type: "string", mapTo: "modelName" },
miles: { type: "int", default: 0 },
},
primaryKey: "_id",
};
}

By default, Realm uses the name defined in the model class to represent classes and fields internally. In some cases, you might want to change this behavior. For example:

  • Para facilitar el trabajo entre plataformas donde las convenciones de nomenclatura difieren. Por ejemplo, si los nombres de las propiedades del esquema de Device Sync usan snake case, mientras que tu proyecto usa camel case.

  • To change a class or field name without forcing a migration.

  • To support multiple model classes with the same name in different packages.

  • To use a class name that is longer than the 57-character limit enforced by Realm.

Puede mapear el nombre de una clase o propiedad en su código a un nombre diferente para almacenar en un realm. Si escribe en un realm sincronizado, el esquema de sincronización ve los valores almacenados utilizando el nombre de clase o propiedad persistido.

Note that migrations must use the persisted class or property name, and any schema errors reported also use the persisted name.

Para usar un nombre de clase diferente en tu código al que está almacenado en un realm:

  1. Set the name property of your Realm object's schema to the name that you want to use to store the object.

  2. Use the class name in the Realm configuration's schema property when you open the realm.

  3. Use the mapped name for performing CRUD operations or when defining Flexible Sync Subscriptions.

In the following example, Realm stores objects created with the Task class as Todo_Item.

class Task extends Realm.Object {
static schema = {
// Set the schema's `name` property to the name you want to store.
// Here, we store items as `Todo_Item` instead of the class's `Task` name.
name: "Todo_Item",
properties: {
_id: "int",
name: "string",
owner_id: "string?",
},
primaryKey: "_id",
};
}
const config = {
// Use the class name in the Configuration's `schema` property when
// opening the realm.
schema: [Task],
sync: {
user: anonymousUser,
flexible: true,
initialSubscriptions: {
update: (subs, realm) => {
subs.add(
realm
// Use the mapped name in Flexible Sync subscriptions.
.objects(`Todo_Item`)
.filtered(`owner_id == "${anonymousUser.id}"`)
);
},
},
},
};
const realm = await Realm.open(config);
realm.write(() => {
// Use the mapped name when performing CRUD operations.
realm.create(`Todo_Item`, {
_id: 12342245,
owner_id: anonymousUser.id,
name: "Test the Todo_Item object name",
});
});
// Use the mapped name when performing CRUD operations.
const assignedTasks = realm.objects(`Todo_Item`);
class Task extends Realm.Object<Task> {
_id!: number;
name!: string;
owner_id?: string;
static schema: ObjectSchema = {
// Set the schema's `name` property to the name you want to store.
// Here, we store items as `Todo_Item` instead of the class's `Task` name.
name: "Todo_Item",
properties: {
_id: "int",
name: "string",
owner_id: "string?",
},
primaryKey: "_id",
};
}
const config: Realm.Configuration = {
// Use the class name in the Configuration's `schema` property when
// opening the realm.
schema: [Task],
sync: {
user: anonymousUser,
flexible: true,
initialSubscriptions: {
update: (subs, realm) => {
subs.add(
realm
// Use the mapped name in Flexible Sync subscriptions.
.objects(`Todo_Item`)
.filtered(`owner_id == "${anonymousUser.id}"`)
);
},
},
},
};
const realm = await Realm.open(config);
realm.write(() => {
// Use the mapped name when performing CRUD operations.
realm.create(`Todo_Item`, {
_id: 12342245,
owner_id: anonymousUser.id,
name: "Test the Todo_Item object name",
});
});
// Use the mapped name when performing CRUD operations.
const assignedTasks = realm.objects(`Todo_Item`);

To use a different property name in your code than is stored in a realm, set mapTo to the name of the property as it appears in your code.

En el siguiente esquema de objeto Car, Realm almacena el nombre del modelo del auto con la propiedad snake case model_name. El esquema asigna la propiedad a modelName para objetos utilizados en el código del cliente.

class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: { type: "objectId", indexed: true },
make: "string",
model_name: { type: "string", mapTo: "modelName" },
miles: { type: "int", default: 0 },
},
primaryKey: "_id",
};
}

Tip

Alternatively, you can define your relationships in your App Services app.

A to-one relationship maps one property to a single instance of another object type. For example, you can model a manufacturer having at most one car as a to-one relationship.

To define a to-one relationship property, specify the related object type name as the property type.

Importante

To-one relationships must be optional

When you declare a to-one relationship in your object model, it must be an optional property. If you try to make a to-one relationship required, Realm throws an exception at runtime.

El siguiente esquema de objeto Manufacturer especifica que un fabricante puede o no fabricar un solo Car. Si fabrican un Car, Realm lo vincula a través de la propiedad car:

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

A to-many relationship maps one property to zero or more instances of another object type. For example, you can model a manufacturer having any number of cars as a to-many relationship.

To define a to-many relationship property, specify the related object type name as a list.

An application could use the following object schemas to indicate that a Manufacturer may make multiple Car objects by including them in its cars property:

class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
// A manufacturer that may have many cars
cars: "Car[]",
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
make: "string",
model: "string",
miles: "int?",
},
};
}

An inverse relationship property is an automatic backlink relationship. Realm automatically updates implicit relationships whenever an object is added or removed in a corresponding to-many list. You cannot manually set the value of an inverse relationship property.

Para definir una propiedad de relación inversa, establezca el tipo de propiedad en linkingObjects y especifique el tipo de objeto y el nombre de la propiedad que definen la relación a invertir.

Una aplicación puede utilizar los siguientes esquemas de objetos para indicar que un Manufacturer puede crear muchos objetos Car y que cada Car debe llevar automáticamente un registro de qué Manufacturer lo crea.

  • The Manufacturer object's cars property is defined as a to-many relationship
    with Car objects and contains all of a given manufacturer's cars.
  • La propiedad assignee del objeto Car invierte la relación y
    automatically updates to refer back to any Manufacturer object that contains the car in its cars property.
class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
// A manufacturer that may have many cars
cars: "Car[]",
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
make: "string",
model: "string",
miles: "int?",
// Backlink to the manufacturer. This is automatically updated whenever
// this car is added to or removed from a manufacturer's cars list.
assignee: {
type: "linkingObjects",
objectType: "Manufacturer",
property: "cars",
},
},
};
}

Para definir un modelo de objeto Realm con un objeto incrustado (objeto Realm anidado), configure embedded en true.

Un objeto incrustado existe como datos anidados dentro de un único objeto principal específico. Hereda el ciclo de vida de su objeto principal y no puede existir como un objeto independiente de Realm. Realm elimina automáticamente los objetos incrustados si se elimina su objeto principal o si se sobrescriben con una nueva instancia de objeto incrustado. Los objetos incrustados no pueden tener una clave principal.

Puede hacer referencia a un tipo de objeto incrustado desde tipos de objetos principales de la misma manera que una relación.

El siguiente ejemplo requiere dos esquemas principales, Manufacturer y Car. La aplicación requiere un esquema secundario Warranty incrustado. Un objeto Manufacturer puede incrustar una lista de Warranty objetos, mientras que un objeto Car solo puede incrustar un único objeto Warranty.

class Manufacturer extends Realm.Object {
static schema = {
name: "Manufacturer",
properties: {
_id: "objectId",
name: "string",
// Embed an array of objects
warranties: { type: "list", objectType: "Warranty" },
},
};
}
class Car extends Realm.Object {
static schema = {
name: "Car",
properties: {
_id: "objectId",
make: "string",
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",
},
};
}

Changed in version 12.2.1.

If you are using Flexible Sync and need to sync a collection unidirectionally from your device to your Atlas database, you can set the asymmetric property on your object schema.

class WeatherSensor extends Realm.Object {
static schema = {
name: "WeatherSensor",
// Sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: "_id",
properties: {
_id: "objectId",
deviceId: "string",
temperatureInFahrenheit: "int",
barometricPressureInHg: "float",
windSpeedInMph: "float",
},
};
}
class WeatherSensor extends Realm.Object<WeatherSensor> {
_id!: Realm.BSON.ObjectId;
deviceId!: string;
temperatureInFahrenheit!: number;
barometricPressureInHg!: number;
windSpeedInMph!: number;
static schema: ObjectSchema = {
name: "WeatherSensor",
// sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: "_id",
properties: {
_id: "objectId",
deviceId: "string",
temperatureInFahrenheit: "int",
barometricPressureInHg: "float",
windSpeedInMph: "float",
},
};
}

In Node.js SDK versions 12.2.0 and earlier, you cannot link from asymmetric objects to Realm.Object types. In SDK versions 12.2.1 and later, asymmetric objects can link to Realm.Object types in addition to embedded objects.

Nota

Attempting to Read Asymmetric Objects

Asymmetric objects cannot be read. If you attempt to query an Asymmetric object, you will get the following error: "Error: You cannot query an asymmetric class.".

Para obtener más información sobre la ingesta de datos, lea Optimizar la sincronización con la ingesta de datos.

Nuevo en la versión 12.9.0.

Starting in Node.js SDK version 12.9.0, you can store collections of mixed data within a mixed property. You can use this feature to model complex data structures, such as JSON or MongoDB documents, without having to define a strict data model.

Unstructured data is data that doesn't easily conform to an expected schema, making it difficult or impractical to model to individual data classes. For example, your app might have highly variable data or dynamic data whose structure is unknown at runtime.

Storing collections in a mixed property offers flexibility without sacrificing functionality, including performant synchronization when using Device Sync. And you can work with them the same way you would a non-mixed collection:

  • Se pueden anidar colecciones mixtas hasta 100 niveles.

  • You can query on and react to changes on mixed collections.

  • You can find and update individual mixed collection elements.

However, storing data in mixed collections is less performant than using a structured schema or serializing JSON blobs into a single string property.

To model unstructured data in your app, define the appropriate properties in your schema as mixed types. You can then set these mixed properties as a list or a dictionary collection of mixed elements. Note that mixed cannot represent a set or an embedded object.

Tip

  • Use a map of mixed data types when the type is unknown but each value will have a unique identifier.

  • Utilice una lista de tipos de datos mixtos cuando el tipo sea desconocido, pero el orden de los objetos sea importante.

Volver

Datos del modelo