This page contains information to quickly get Realm integrated into your app.
If you haven't already, install the Realm Node.js SDK.
Import Realm
At the top of your source files where you want to use Realm, add the following line to import the SDK and the BSON library.
import Realm, { BSON } from "realm";
Define tu modelo de objeto
Your application's object model defines the data that you can store within Realm.
Para definir un tipo de objeto Realm, cree un objeto de esquema que especifique el tipo
name propertiesy. 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.
El siguiente código muestra cómo definir un modelo de objeto para un objeto Task. En este ejemplo:
El
primaryKeyes el_iddel tipoint. Otro tipo común usado para llaves primarias es ObjectId.El campo
namees requerido.The
statusandowner_idfields are optional, denoted by the question mark immediately after the data type.
export class QuickstartTask extends Realm.Object { static schema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
export class QuickstartTask extends Realm.Object<Task> { _id!: BSON.ObjectID; name!: string; status?: string; owner_id?: string; static schema: ObjectSchema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
Abrir un reino
Para abrir un reino, pasa un Objeto Realm.BaseConfiguration para Realm.open().
const realm = await Realm.open({ schema: [QuickstartTask], });
Find, Sort, and Filter Objects
El siguiente código demuestra cómo:
Query for all instances of the "Task" object type.
Filtra la consulta para recuperar sólo las tareas que están "Abiertas".
Ordena las tareas por el nombre en orden ascendente.
// Query for specific obect using primary key. const specificTask = realm.objectForPrimaryKey(QuickstartTask, testId); // Query realm for all instances of the "Task" type. const tasks = realm.objects(QuickstartTask); // Filter for all tasks with a status of "Open". const openTasks = tasks.filtered("status = 'Open'"); // Sort tasks by name in ascending order. const tasksByName = tasks.sorted("name");
Crear, modificar y eliminar objetos de Realm
Once you have opened a realm, you can create, modify, and delete objects in it. All write operations must occur within a write transaction.
const allTasks = realm.objects(QuickstartTask); // Add a couple of Tasks in a single, atomic transaction. realm.write(() => { realm.create(QuickstartTask, { _id: firstId, name: "go grocery shopping", status: "Open", }); realm.create(QuickstartTask, { _id: secondId, name: "go exercise", status: "Open", }); }); const task1 = allTasks.find( (task) => task._id.toString() == firstId.toString() ); const task2 = allTasks.find( (task) => task._id.toString() == secondId.toString() ); realm.write(() => { // Modify an object. task1!.status = "InProgress"; // Delete an object. realm.delete(task2!); });
Ver una colección
Puedes monitorizar un realm, una colección o un objeto para detectar cambios registrando controladores de eventos con el Realm.addListener() Object.addListener() Métodos Collection.addListener()
Importante
El orden importa
En los controladores de notificaciones de colecciones, aplique siempre los cambios en el siguiente orden: eliminaciones, inserciones y modificaciones. Gestionar las inserciones antes de las eliminaciones puede provocar un comportamiento inesperado.
En el siguiente ejemplo, un desarrollador de aplicaciones observa los cambios en la colección Task.
// Define the collection notification listener. const listener = (tasks, changes) => { // Update UI in response to deleted objects. changes.deletions.forEach((index) => { // Deleted objects cannot be accessed directly, // but we can update a UI list, etc. knowing the index. console.log(`A task was deleted at the ${index} index.`); // ... }); // Update UI in response to inserted objects. changes.insertions.forEach((index) => { const insertedTasks = tasks[index]; console.log(`insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}`); // ... }); // Update UI in response to modified objects. // `newModifications` contains an index to the modified object's position // in the collection after all deletions and insertions have been applied. changes.newModifications.forEach((index) => { const modifiedTask = tasks[index]; console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`); // ... }); }; // Observe collection notifications. tasks.addListener(listener);
// Define the collection notification listener. //@ts-expect-error TYPEBUG: OrderedCollection is incorrectly implemented const listener: Realm.CollectionChangeCallback = ( tasks: Realm.OrderedCollection<QuickstartTask>, changes: Realm.CollectionChangeSet ) => { // Update UI in response to deleted objects. changes.deletions.forEach((index) => { // Deleted objects cannot be accessed directly, // but we can update a UI list, etc. knowing the index. console.log(`A task was deleted at the ${index} index.`); // ... }); // Update UI in response to inserted objects. changes.insertions.forEach((index) => { const insertedTasks = tasks[index]; console.log(`insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}`); // ... }); // Update UI in response to modified objects. // `newModifications` contains an index to the modified object's position // in the collection after all deletions and insertions have been applied. changes.newModifications.forEach((index) => { const modifiedTask = tasks[index]; console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`); // ... }); }; // Observe collection notifications. //@ts-expect-error TYPEBUG: OrderedCollection is incorrectly implemented tasks.addListener(listener);
Close a Realm
Llama al realm.close() método cuando se termine con una instancia Realm para evitar fugas de memoria.
// Close the realm. realm.close();
Agregar sincronización de dispositivos (opcional)
This section illustrates how to authenticate with an Anonymous User and open a Flexible Sync realm to sync data between devices.
Requisitos previos
Autenticación anónima habilitada en la interfaz de usuario de App Services
Sincronización flexible habilitada con el modo de desarrollo activado y un
owner_idcampo en el Queryable Fields sección
Inicializar la aplicación
To use App Services features, such as authentication and sync, you must first access your App Services App using your App ID. You can find your App ID in the App Services UI.
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", });
Authenticate a User
To authenticate and log in a user, call App.logIn(). When anonymous authentication is enabled, users can immediately log into your app without providing any identifying information:
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. const anonymousUser = await app.logIn(Realm.Credentials.anonymous());
Define un modelo de objeto
Los modelos de objeto para dominios sincronizados funcionan igual que los dominios locales. Define tu modelo de objeto como lo harías para un dominio local.
export class QuickstartTask extends Realm.Object { static schema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
export class QuickstartTask extends Realm.Object<Task> { _id!: BSON.ObjectID; name!: string; status?: string; owner_id?: string; static schema: ObjectSchema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
Open a Synced Realm
Una vez que hayas inicializado tu aplicación, autenticado un usuario y definido tu Modelo de objeto, puedes crear una SyncConfiguration.
Para abrir un dominio de Sincronización Flexible, llame a Realm.open(). Pase un objeto BaseConfiguration, que debe incluir la sync propiedad que define un objeto SyncConfiguration. Para usar la Sincronización Flexible, en SyncConfiguration, debe incluir user flexible: truey.
Además, necesitas al menos una suscripción antes de poder leer o guardar en el realm. Usa Configuration.sync.initialSubscriptions para definir el conjunto inicial de suscripciones cuando el archivo Realm se abre por primera vez.
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. const anonymousUser = await app.logIn(Realm.Credentials.anonymous()); // Create a `SyncConfiguration` object. const config = { schema: [QuickstartTask], sync: { // Use the previously-authenticated anonymous user. user: anonymousUser, // Set flexible sync to true to enable sync. flexible: true, // Define initial subscriptions to start syncing data as soon as the // realm is opened. initialSubscriptions: { update: (subs, realm) => { subs.add( // Get objects that match your object model, then filter them by // the `owner_id` queryable field realm .objects(QuickstartTask) .filtered(`owner_id == "${anonymousUser.id}"`) ); }, }, }, }; const realm = await Realm.open(config);
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. const anonymousUser = await app.logIn(Realm.Credentials.anonymous()); // Create a `SyncConfiguration` object. const config: Realm.Configuration = { schema: [QuickstartTask], sync: { // Use the previously-authenticated anonymous user. user: anonymousUser, // Set flexible sync to true to enable sync. flexible: true, // Define initial subscriptions to start syncing data as soon as the // realm is opened. initialSubscriptions: { update: (subs, realm) => { subs.add( // Get objects that match your object model, then filter them by // the `owner_id` queryable field realm .objects(QuickstartTask) .filtered(`owner_id == "${anonymousUser.id}"`) ); }, }, }, }; const realm = await Realm.open(config);
The syntax to read, write, and watch for changes on a synced realm is identical to the syntax for non-synced realms above. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.