Docs Menu

Docs HomeRealm

Open & Close a Realm - Node.js SDK

On this page

  • Open a Local Realm
  • Open an In-Memory Realm
  • Open a Synced Realm
  • Open a Flexible Synced Realm
  • Open a Partition-Based Synced Realm
  • Open a Synced Realm While Offline
  • Open Immediately with Background Sync
  • Open After Timeout with Background Sync
  • Copy Data and Open a New Realm
  • Close a Realm

To open a local (non-synced) realm, pass a Realm.Configuration object to the asynchronous method Realm.open().

Note

Accessing the Default Realm Path

If the path property is not specified in your Configuration object, the default path is used. You can access and change the default Realm path using the Realm.defaultPath global property.

const Car = {
name: "Car",
properties: {
make: "string",
model: "string",
miles: "int",
},
};
// Open a local realm file with a particular path & predefined Car schema
try {
const realm = await Realm.open({
schema: [Car],
});
realm.close();
} catch (err) {
console.error("Failed to open the realm", err.message);
}

To create a realm that runs entirely in memory without being written to a file, add inMemory: true to your Realm.Configuration object:

const realm = await Realm.open({
inMemory: true,
schema: [Car],
});

Note

In-memory realms may use disk space if memory is running low, but files created by an in-memory realm are deleted when you close the realm.

You can open a Synced realm with a Flexible Sync or Partition-Based Sync. If you have not yet decided or are unsure which to use, read the Choose Your Sync Mode page.

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.

To open a realm using Flexible Sync, call Realm.open(). Pass in a Configuration object, which must include the sync property defining a SyncConfiguration object. In the SyncConfiguration, you must include include a user and flexible:true.

const realm = await Realm.open({
schema: [TaskSchema, TeamSchema],
sync: {
user: app.currentUser,
flexible: true,
},
});

Important

Flexible Sync Requires a Subscription

You can't use a Flexible Sync realm until you add at least one subscription. To learn how to add subscriptions, see: Add a Query to the List Of Subscriptions.

To open a realm with Partition-Based Sync, call Realm.open(). Pass in a Configuration object, which must include the sync property defining a SyncConfiguration object. In the SyncConfiguration, you must include include user and partitionValue.

const config = {
schema: [Car], // predefined schema
sync: {
user: app.currentUser, // already logged in user
partitionValue: "myPartition",
},
};
try {
const realm = await Realm.open(config);
realm.close();
} catch (err) {
console.error("failed to open realm", err.message);
}

When your Realm application authenticates a user, it caches the user's credentials. You can check for existing user credentials to bypass the login flow and access the cached user. Use this to open a realm offline.

Note

Initial login requires a network connection

When a user signs up for your app, or logs in for the first time with an existing account on a client, the client must have a network connection. Checking for cached user credentials lets you open a realm offline, but only if the user has previously logged in while online.

// Log the user into the backend app.
// The first time you login, the user must have a network connection.
const getUser = async () => {
// Check for an existing user.
// If the user is offline but credentials are
// cached, this returns the existing user.
if (app.currentUser) return app.currentUser;
// If the device has no cached user credentials, log them in.
const credentials = Realm.Credentials.anonymous();
return await app.logIn(credentials);
};

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.

Important

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 either Flexible and Partition-Based Sync.

If the user's device is not connected to the internet or you're uncertain of it's connection status, set the realm behavior's type to openImmediately. This syncs data from the server in the background.

const openRealmBehaviorConfig = {
type: "openImmediately",
};
const config = {
schema: [Car], // predefined schema
sync: {
user: await getUser(),
partitionValue: "myPartition",
newRealmFileBehavior: openRealmBehaviorConfig,
existingRealmFileBehavior: openRealmBehaviorConfig,
},
};

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:

  • the timeout period elapses.

  • the realm has completely downloaded.

If the realm doesn't finish downloading before the timeout, the initial realm sync continues in the background.

const openRealmBehaviorConfig = {
type: "downloadBeforeOpen",
timeOut: 1000,
timeOutBehavior: "openLocalRealm",
};
const config = {
schema: [Car], // predefined schema
sync: {
user: await getUser(), // already logged in user
partitionValue: "myPartition",
existingRealmFileBehavior: openRealmBehaviorConfig,
newRealmFileBehavior: openRealmBehaviorConfig,
},
};

New in version 10.14.0.

To copy data from an existing realm to a new realm with different configuration options, pass the new configuration the Realm.writeCopyTo() method.

Note

Partition-Based Sync Only

This method only supports Partition-Based Sync. If your app uses Flexible Sync, you must manually iterate through the objects in one realm and copy them into the other realm.

In the new realm's configuration, you must specify the path.

If you write the copied realm to a realm file that already exists, the data is written object by object. The copy operation replaces objects if there already exists objects for given primary keys. The schemas of the realm you copy and the realm you are writing to must be compatible for the copy operation to succeed. Only objects in the schemas of both configurations are copied over.

The configuration change can include modifications to SyncConfiguration:

  • Local realm to synced realm

  • Synced Realm to local realm

The configuration change can also include changes to encryptionKey property of the Configuration:

  • Encrypted realm to unencrypted realm

  • Unencrypted realm to encrypted realm

Example

Convert Local Realm to Synced Realm

const localConfig = {
schema: [Car],
path: "localOnly.realm",
};
const localRealm = await Realm.open(localConfig);
const syncedConfig = {
schema: [Car], // predefined schema
path: "copyLocalToSynced.realm", // must include in output configuration
sync: {
user: app.currentUser, // already logged in user
partitionValue: "myPartition",
},
};
localRealm.writeCopyTo(syncedConfig);
const syncedRealm = await Realm.open(syncedConfig);

You can also combine changes to configuration. For example, you can open a local encrypted realm as a synced unencrypted realm or a unencrypted synced realm as an encrypted synced realm.

Example

Convert Synced Encrypted to Local Unencrypted Realm

const encryptionKey = new Int8Array(64); // Create a secure key
// ... store key ...
const syncedEncryptedConfig = {
schema: [Car], // predefined schema
path: "syncedEncrypted.realm", // must include in output configuration
sync: {
user: app.currentUser, // already logged in user
partitionValue: "myPartition",
},
encryptionKey,
};
const syncedEncryptedRealm = await Realm.open(syncedEncryptedConfig);
const localUnencryptedConfig = {
schema: [Car], // predefined schema
path: "copyLocalUnencrypted.realm", // must include in output configuration
};
syncedEncryptedRealm.writeCopyTo(localUnencryptedConfig);
const localUnencryptedRealm = await Realm.open(syncedEncryptedConfig);

Tip

It is important to remember to call the close() method when done with a realm instance to avoid memory leaks.

realm.close();
←  Define a Realm Object Schema - Node.js SDKRead & Write Data - Node.js SDK →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.