Quick Start - Node.js SDK
On this page
Overview
This page contains information to quickly get Realm Database 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.
import Realm from "realm";
Define Your Object Model
Your application's object model defines the data that you can store within Realm Database.
To define a Realm object type, create a schema object that specifies the type's
name
and properties
. The type name must be unique among object types in
a realm. For details on how to define specific properties, see Define
Object Properties.
The following code shows how to define an object model for a Task
object. In this example:
The
primaryKey
is the_id
of typeint
. Another common type used for primary keys is ObjectId.The
name
field is required.The
status
andonwer_id
fields are optional, denoted by the question mark immediately after the data type.
const TaskSchema = { name: "Task", properties: { _id: "int", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", };
Open a Realm
To open a realm, pass a Realm.Configuration object to Realm.open().
const realm = await Realm.open({ path: "realm-files/myrealm", schema: [TaskSchema], });
Create Realm Objects
Once you have opened a realm, you can create objects in it. All writes must occur within a write transaction.
// Add a couple of Tasks in a single, atomic transaction let task1, task2; realm.write(() => { task1 = realm.create("Task", { _id: 1, name: "go grocery shopping", status: "Open", }); task2 = realm.create("Task", { _id: 2, name: "go exercise", status: "Open", }); console.log(`created two tasks: ${task1.name} & ${task2.name}`); }); // use task1 and task2
Find, Sort, and Filter Objects
The following code demonstrates how to:
Query for all instances of the "Task" object type.
Filter the query to retrieve only the tasks that are "Open".
Sort the tasks by the name in an ascending order.
// query realm for all instances of the "Task" type. const tasks = realm.objects("Task"); console.log(`The lists of tasks are: ${tasks.map((task) => task.name)}`); // filter for all tasks with a status of "Open" const openTasks = tasks.filtered("status = 'Open'"); console.log( `The lists of open tasks are: ${openTasks.map( (openTask) => openTask.name )}` ); // Sort tasks by name in ascending order const tasksByName = tasks.sorted("name"); console.log( `The lists of tasks in alphabetical order are: ${tasksByName.map( (taskByName) => taskByName.name )}` );
Modify an Object
As with writes, any changes to a Realm object must occur within a Write transaction block. To modify an object, you update the object properties:
In the following example, an application developer updates task1
from the
Create Realm Objects
example above. The developer begins progress on the "go grocery shopping
task" and sets task1
to "InProgress".
realm.write(() => { task1.status = "InProgress"; });
Delete an Object
You can delete an object by calling the realm.delete() method within a write transaction block:
In the following example, an application developer deletes task1
from the
Create Realm Objects
example above.
realm.write(() => { // Delete the task from the realm. realm.delete(task1); // Discard the reference. task1 = null; });
Watch a Collection
You can watch a realm, collection, or object for changes by registering event handlers with the Realm.addListener() Object.addListener() Collection.addListener() methods.
In the following example, an application developer watches for changes to the
Task
collection.
// Define the collection notification listener function 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) => { let insertedTasks = tasks[index]; console.log( `insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}` ); // ... }); // Update UI in response to modified objects // `newModifications` contains object indexes from after they were modified changes.newModifications.forEach((index) => { let modifiedTask = tasks[index]; console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`); // ... }); } // Observe collection notifications. tasks.addListener(listener);
Close a Realm
Call the realm.close() method when done with a realm instance to avoid memory leaks.
// Remember to close the realm realm.close();
Add Device Sync (Optional)
This section illustrates how to authenticate with an Anonymous User and open a Flexible Sync realm to sync data between devices.
Prerequisites
Anonymous authentication enabled in the App Services UI
Flexible Sync enabled with Development Mode on and an
owner_id
field in the Queryable Fields section
Initialize the App
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. await app.logIn(Realm.Credentials.anonymous());
Define an Object Model
Object models for synced realms work the same way as local-only Realms. Define your object model just as you would for a local-only Realm.
const TaskSchema = { name: "Task", properties: { _id: "int", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", };
Open a Synced Realm
After you have initialized your App, authenticated a user, and defined your object model, you can create a SyncConfiguration.
To open a Flexible Sync realm, call Realm.open().
Pass in a Configuration
object, which must include the sync
property defining a
SyncConfiguration object.
To use Flexible Sync, in the SyncConfiguration, you must include include a
user
and flexible: true
.
Additionally, you need at least one subscription before you can read from or write to the
realm. Use Configuration.sync.initialSubscriptions
to define the initial
subscription set when the Realm file is first opened.
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. await app.logIn(Realm.Credentials.anonymous()); // Define an object model const TaskSchema = { name: "Task", properties: { _id: "int", name: "string", status: "string?", progressMinutes: "int?", owner: "string?", dueDate: "date?", }, primaryKey: "_id", }; // Create a `SyncConfiguration` object. const config = { schema: [TaskSchema], sync: { // Use the previously-authenticated anonymous user. user: app.currentUser, // 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 // the `owner_id` queryable field realm.objects("Task").filtered(`owner_id = ${app.currentUser.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.