Realms sincronizados
You can configure a realm to automatically synchronize data between many devices that each have their own local copy of the data. Synced realms use a different configuration than local-only realms and require an Atlas App Services backend to handle the synchronization process.
Las aplicaciones siempre pueden crear, modificar y eliminar objetos de dominio sincronizados localmente, incluso sin conexión. Siempre que haya una conexión de red disponible, el SDK de dominio abre una conexión con un servidor de aplicaciones y sincroniza los cambios con y desde otros clientes. El protocolo Atlas Device Sync y las transformaciones operativas del lado del servidor garantizan que todas las instancias totalmente sincronizadas de un reino vean exactamente los mismos datos, incluso si algunos cambios ocurrieron sin conexión y/o se recibieron fuera de orden.
Tip
Learn How to Configure and Use Sync
For more information on synced realms, including directions on how to set up sync in a Realm app, see Atlas Device Sync Overview.
Requisitos previos
Before you configure a realm with Flexible Sync in a Node.js application:
Enable Flexible Sync on the backend. You must configure Flexible Sync in the backend before you can use it with your client application.
Authenticate a user in your client project.
Open a Synced Realm
El primer paso para implementar la Sincronización de Dispositivos es abrir el dominio sincronizado. La siguiente información corresponde a una aplicación que utiliza la Sincronización Flexible. Si su aplicación utiliza la sincronización basada en particiones, consulte "Abrir un dominio sincronizado basado en particiones". Si aún no ha decidido o no está seguro de cuál usar, consulte la página "Elija su modo de sincronización".
Para abrir un reino usando Sincronización flexible, llame a Realm.open(). Pase un objeto ConfigurationWithSync, que debe incluir el sync Propiedad que define un objeto SyncConfiguration. En SyncConfiguration, debe incluir user flexible:truey.
const realm = await Realm.open({ schema: [TaskSchema, TeamSchema], sync: { user: app.currentUser, flexible: true, }, });
By default, Realm syncs all data from the server before returning. If you want to sync data in the background, read the Open a Synced Realm While Offline section.
Importante
Flexible Sync Requiere una suscripción
You can't use a Flexible Sync realm until you add at least one subscription. To learn how to add subscriptions, see: Add a Subscription.
Open Synced Realm at Specific Path
New in version realm@11.6.0.
Using AppConfiguration.baseFilePath, and Realm.Configuration.path, you can control where Realm and metadata files are stored on client devices.
To do so, set <AppProvider>.baseFilePath. If baseFilePath is not set, the current work directory is used. You can also set <RealmProvider>.sync.path for more control.
const app = new Realm.App({ id: APP_ID, baseFilePath: customPath }); const user = await app.logIn(Realm.Credentials.anonymous()); const realm = await Realm.open({ schema: [Car], sync: { flexible: true, user, }, });
If baseFilePath is set, metadata is always stored in <baseFilePath>/mongodb-realm/. If baseFilePath isn't set, then metadata is stored in <Realm.defaultPath>/mongodb-realm.
La ubicación exacta de tu archivo Realm puede variar dependiendo de cómo configures Realm.Configuration.path:
Realm.Configuration.pathno está configurado ybaseFilePathestá configurado. Tu archivo Realm está almacenado enbaseFilePath.Realm.Configuation.pathis set to a relative path. Your Realm file is stored relative tobaseFilePath.Realm.Configuration.pathis an absolute path. Your Realm file is stored atRealm.Configuration.path.
Open a Synced Realm While Offline
Cuando tu aplicación Realm autentica a un usuario, almacena en caché las credenciales del usuario. Puedes comprobar si existen credenciales de usuario para omitir el flujo de inicio de sesión y acceder al usuario almacenado en caché. Usa esto para abrir un realm sin conexión.
Nota
El inicio de sesión inicial requiere una conexión de red
Cuando un usuario se registra en tu aplicación o inicia sesión por primera vez con una cuenta existente en un cliente, este debe tener conexión de red. Comprobar las credenciales de usuario en caché permite abrir un reino sin conexión, pero solo si el usuario ha iniciado sesión previamente con conexión.
// Log user into your App Services App. // On first login, the user must have a network connection. const getUser = async () => { // If the device has no cached user credentials, log in. if (!app.currentUser) { const credentials = Realm.Credentials.anonymous(); await app.logIn(credentials); } // If the app is offline, but credentials are // cached, return existing user. return app.currentUser!; };
The following subsections show how to use background synchronization to access a realm while offline. To do this, use the cached user and an OpenRealmBehaviorConfiguration object.
Within your Sync Configuration, set the optional newRealmFileBehavior and existingRealmFileBehavior fields to your OpenRealmBehaviorConfiguration object to enable background synchronization.
Importante
Offline Login is Supported for Both Flexible and Partition-Based Sync Configurations
You can open a realm immediately with background sync or after a timeout elapses using Flexible Sync or the older Partition-Based Sync.
Partition-Based Sync is an outdated sync mode. See the Partition-Based Sync - Node.js SDK page for details on using Partition-Based Sync for your application.
Abrir inmediatamente con sincronización en segundo plano
Si el dispositivo del usuario no está conectado a Internet o hay incertidumbre sobre el estado de su conexión, establecer el tipo de comportamiento del realm como openImmediately. Esto sincroniza los datos desde el servidor en segundo plano.
const behaviorConfiguration = { type: "openImmediately", }; const config = { schema: [Car], sync: { user: await getUser(), flexible: true, newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: "openImmediately", }; const config: Realm.Configuration = { schema: [Car], sync: { user: await getUser(), flexible: true, newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
Open After Timeout with Background Sync
If you want to sync data but you're in an environment where it's uncertain if the user has an Internet connection, specify a timeOut. This automatically opens the realm when either:
transcurre el tiempo de espera.
the realm has completely downloaded.
If the realm doesn't finish downloading before the timeout, the initial realm sync continues in the background.
const behaviorConfiguration = { type: "openImmediately", timeOut: 1000, timeOutBehavior: "openLocalRealm", }; const config = { schema: [Car], sync: { flexible: true, user: await getUser(), existingRealmFileBehavior: behaviorConfiguration, newRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: "openImmediately", timeOut: 1000, timeOutBehavior: "openLocalRealm", }; const config: Realm.Configuration = { schema: [Car], sync: { flexible: true, user: await getUser(), existingRealmFileBehavior: behaviorConfiguration, newRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
Sync Changes in the Background
Puede que desees sincronizar los cambios en segundo plano para mostrar datos parciales al usuario mientras el realm sincronizado descarga los datos del servidor, evitando así que la experiencia de usuario se bloquee. Recomendamos sincronizar los cambios en segundo plano para aplicaciones en las que el dispositivo del usuario pueda quedarse sin conexión. Para sincronizar cambios en segundo plano, abre un realm sincronizado de forma síncrona.
Cree un objeto OpenRealmBehaviorConfiguration y establezca su type "openImmediately"en.
const behaviorConfiguration = { type: "openImmediately", };
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: Realm.OpenRealmBehaviorType.OpenImmediately, };
Create a Configuration object, which must include the sync property defining a SyncConfiguration object. Set this OpenRealmBehaviorConfiguration object as the value for the newRealmFileBehavior and existingRealmFileBehavior fields of the SyncConfiguration.
const config = { schema: [DogSchema], sync: { user: app.currentUser, partitionValue: "MyPartitionValue", // The behavior to use when this is the first time opening a realm. newRealmFileBehavior: behaviorConfiguration, // The behavior to use when a realm file already exists locally, // i.e. you have previously opened the realm. existingRealmFileBehavior: behaviorConfiguration, }, };
const config: Realm.Configuration = { schema: [DogSchema], sync: { user: app.currentUser!, partitionValue: "MyPartitionValue", // The behavior to use when this is the first time opening a realm. newRealmFileBehavior: behaviorConfiguration, // The behavior to use when a realm file already exists locally, // i.e. you have previously opened the realm. existingRealmFileBehavior: behaviorConfiguration, }, };
Finalmente, llama a Realm.open() para abrir un reino sincronizado. Esto creará una sesión de sincronización y comenzará a descargar los datos existentes del servidor en segundo plano.
const realm = await Realm.open(config);
Cancel Asynchronous Operations after a Timeout
New in version 12.0.0.
Puedes especificar una propiedad cancelWaitsOnNonFatalErrors en tu objeto BaseSyncConfiguration.
trueCuando, el SDK de Node.js cancela las operaciones asíncronas, como la espera de cargas o descargas, al transcurrir un tiempo de espera. Puede definir el tiempo de espera para esta opción en AppConfiguration. Para ver un ejemplo, consulte Configurar un tiempo de espera para el cliente de la aplicación.
This property defaults to false if you do not specify a value.
const config = { schema: [Doggie], sync: { flexible: true, user: app.currentUser, // When `true`, upload and download waits are canceled on any // error, such as a timeout, instead of just a fatal error. // You can provide an optional timeouts property in milliseconds. cancelWaitsOnNonFatalError: true, }, };
const config: Realm.Configuration = { schema: [Doggie], sync: { flexible: true, user: app.currentUser!, // When `true`, upload and download waits are canceled on any // error, such as a timeout, instead of just a fatal error. // You can provide an optional timeouts property in milliseconds. cancelWaitsOnNonFatalError: true, }, };