Navigation

Quick Start

Overview

This page contains information to quickly get Realm Database integrated into your app. Before you begin, ensure you have:

Import Realm

At the top of your source files where you want to use MongoDB Realm, add the following line to import the SDK.

import * as Realm from "realm";
const Realm = require("realm");

Initialize the App

To use MongoDB Realm features such as authentication and sync, you must access your Realm app using your Realm app ID. You can find your Realm app ID in the Realm UI.

const app = new Realm.App({ id: "<Your App ID>" });
const app = new Realm.App({ id: "<Your App ID>" });

Define Your Object Model

If you have not enabled Realm Sync or you enabled Sync with Development Mode, you can define your object model directly in code.

Note

If you have enabled Sync but turned off Development Mode, you can copy and paste the object model definitions that Realm generated for you from the SDKs tab in the Realm UI. You must re-enable Development Mode if you want to make changes to the object model definition from client-side code. For more information, see Configure Your Data Model.

import BSON from 'bson';

type Task = {
  _id: BSON.ObjectId;
  _partition?: string;
  name: string;
  status: string;
};

const TaskSchema = {
  name: 'Task',
  properties: {
    _id: 'objectId',
    _partition: 'string?',
    name: 'string',
    status: 'string',
  },
  primaryKey: '_id',
};
const TaskSchema = {
  name: 'Task',
  properties: {
    _id: 'objectId',
    _partition: 'string?',
    name: 'string',
    status: 'string',
  },
  primaryKey: '_id',
};

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:

const app = new Realm.App({ id: "<Your App ID>" });
async function handleLogin() {
  // Create a Credentials object to identify the user.
  // Anonymous credentials don't have any identifying information, but other
  // authentication providers accept additional data, like a user's email and
  // password.
  const credentials: Realm.Credentials = Realm.Credentials.anonymous();
  // You can log in with any set of credentials using `app.logIn()`
  const user: Realm.User = await app.logIn(credentials);
  console.log(`Logged in with the user id: ${user.id}`);
};
run().catch(err => {
  console.error("Failed to log in:", err)
});
const app = new Realm.App({ id: "<Your App ID>" });
async function handleLogin() {
  // Create a Credentials object to identify the user.
  // Anonymous credentials don't have any identifying information, but other
  // authentication providers accept additional data, like a user's email and
  // password.
  const credentials = Realm.Credentials.anonymous();
  // You can log in with any set of credentials using `app.logIn()`
  const user = await app.logIn(credentials);
  console.log(`Logged in with the user id: ${user.id}`);
};
run().catch(err => {
  console.error("Failed to log in:", err)
});

Open a Realm

Once you have enabled Realm Sync and authenticated a user, you can open a synced realm by calling Realm.open():

const app = new Realm.App({ id: "<Your App ID>" });
async function run() {
  await app.logIn(new Realm.Credentials.anonymous());
  // When you open a synced realm, the SDK automatically automatically
  // creates the realm on the device (if it didn't exist already) and
  // syncs pending remote changes as well as any unsynced changes made
  // to the realm on the device.
  const realm: Realm = await Realm.open({
    schema: [TaskModel],
    sync: {
      user: app.currentUser?,
      partitionValue: "myPartition",
    },
  });

  // The myPartition realm is now synced to the device. You can
  // access it through the `realm` object returned by `Realm.open()`
}
run().catch(err => {
  console.error("Failed to open realm:", err)
});
const app = new Realm.App({ id: "<Your App ID>" });
async function run() {
  await app.logIn(new Realm.Credentials.anonymous());
  // When you open a synced realm, the SDK automatically automatically
  // creates the realm on the device (if it didn't exist already) and
  // syncs pending remote changes as well as any unsynced changes made
  // to the realm on the device.
  const realm = await Realm.open({
    schema: [TaskModel],
    sync: {
      user: app.currentUser,
      partitionValue: "myPartition",
    },
  });

  // The myPartition realm is now synced to the device. You can
  // access it through the `realm` object returned by `Realm.open()`
}
run().catch(err => {
  console.error("Failed to open realm:", err)
});

See also

Sync Data

Create, Read, Update, and Delete Objects

Once you have opened a realm, you can modify it and its objects in a write transaction block.

Create New Objects

To create a new object, start a new transaction by calling Realm.write() and then call Realm.create() in the transaction callback function:

realm.write(() => {
  const newTask: Task = realm.create("Task", {
    _id: new BSON.ObjectID(),
    name: "go grocery shopping",
    status: "Open",
  });
});
realm.write(() => {
  const newTask = realm.create("Task", {
    _id: new BSON.ObjectID(),
    name: "go grocery shopping",
    status: "Open",
  });
});

Get a Collection of Objects

You can retrieve a live collection that contains all objects of a given type in the realm:

// Query realm for all instances of the "Task" type.
const tasks: Realm.Collection<Task> = realm.objects<Task>("Task");
// Query realm for all instances of the "Task" type.
const tasks = realm.objects("Task");

Filter & Query Collections

You can filter the objects in a collection by providing a query filter:

const tasks: Realm.Collection<Task> = realm.objects<Task>("Task");
const openTasks: Realm.Collection<Task> = tasks.filtered("status = 'Open'");
console.log(`${openTasks.length} tasks are Open (Total tasks: ${tasks.length})`);
const tasks = realm.objects("Task");
const openTasks = tasks.filtered("status = 'Open'");
console.log(`${openTasks.length} tasks are Open (Total tasks: ${tasks.length})`);

Modify an Object

To modify an object, update its properties in a Realm.write() transaction block:

const tasks: Realm.Collection<Task> = realm.objects<Task>("Task");
const someTask: Task = tasks.filtered("status = 'Open' LIMIT(1)")[0];
realm.write(() => {
  someTask.status = 'InProgress';
});
const tasks = realm.objects("Task");
const someTask = tasks.filtered("status = 'Open' LIMIT(1)")[0];
realm.write(() => {
  someTask.status = 'InProgress';
});

Delete an Object

To delete an object, pass it to Realm.delete() in a Realm.write() transaction block:

const tasks: Realm.Collection<Task> = realm.objects<Task>("Task");
let someTask: Task | null = tasks.filtered("status = 'Open' LIMIT(1)")[0];
realm.write(() => {
  // Delete the task from the realm.
  realm.delete(someTask);
  // Discard the reference.
  someTask = null;
});
const tasks = realm.objects("Task");
let someTask = tasks.filtered("status = 'Open' LIMIT(1)")[0];
realm.write(() => {
  // Delete the task from the realm.
  realm.delete(someTask);
  // Discard the reference.
  task = null;
});

Watch for Changes

You can watch a realm, collection, or object for changes by registering event handlers with the Realm.addListener() Object.addListener() Collection.addListener() methods.

// Query realm for all instances of the "Task" type.
const tasks = realm.objects("Task");

// Define the collection notification listener
const listener: Realm.CollectionChangeCallback<Task> = (
  tasks: Realm.Collection<Task>,
  changes: Realm.ObjectChanges
) => {
  // Update in response to deleted objects
  (changes.deletions as number[]).forEach((index: number) => {
    // Deleted objects cannot be accessed directly,
    // but we can update a UI list, etc. knowing the index.
  });

  // Update in response to inserted objects
  (changes.insertions as number[]).forEach((index: number) => {
    const insertedTask = tasks[index];
    // ...
  });

  // Update UI in response to modified objects
  // `oldModifications` contains object indexes from before they were modified
  (changes.oldModifications as number[]).forEach((index: number) => {
    let modifiedTask = tasks[index];
    // ...
  });

  // Update UI in response to modified objects
  // `newModifications` contains object indexes from before they were modified
  (changes.newModifications as number[]).forEach((index: number) => {
    let modifiedTask = tasks[index];
    // ...
  });
}

// Observe collection notifications.
tasks.addListener(listener);
// Query realm for all instances of the "Task" type.
const tasks = realm.objects("Task");

// 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.
  });

  // Update UI in response to inserted objects
  changes.insertions.forEach((index) => {
    let insertedTasks = tasks[index];
    // ...
  });

  // Update UI in response to modified objects
  // `oldModifications` contains object indexes from before they were modified
  changes.oldModifications.forEach((index) => {
    let modifiedTask = tasks[index];
    // ...
  });

  // Update UI in response to modified objects
  // `newModifications` contains object indexes from before they were modified
  changes.newModifications.forEach((index) => {
    let modifiedTask = tasks[index];
    // ...
  });
}

// Observe collection notifications.
tasks.addListener(listener);

To remove all registered realm, object, and collection listeners associated with a realm, call Realm.removeAllListeners().

To remove a specific listener, call Object.removeListener() on the object that is being watched with the listener function as the argument.

// Unregister all listeners
realm.removeAllListeners();

// Unregister a specific listener:
tasks.removeListener(listener);
// Unregister all listeners
realm.removeAllListeners();

// Unregister a specific listener:
tasks.removeListener(listener);

Log Out

You can log out an authenticated user by calling User.logOut():

app.currentUser?.logOut();
app.currentUser.logOut();

Complete Example

Code

The following code is a fully runnable example that includes all of the concepts on this page. Make sure to replace <Your App ID> with your App ID.

import * as Realm from "realm";
import { ObjectId } from "bson";

// Update this with your App ID
const app = new Realm.App({ id: "<Your App ID>" });

type Task = {
  _id: ObjectId;
  _partition?: string;
  name: string;
  status: string;
};
const TaskSchema = {
  name: "Task",
  properties: {
    _id: "objectId",
    _partition: "string?",
    name: "string",
    status: "string",
  },
  primaryKey: "_id",
};

async function run() {
  const credentials = Realm.Credentials.anonymous();
  await app.logIn(credentials);
  console.log(`Logged in anonymously with user id: ${app.currentUser?.id}`);

  const realm: Realm = await Realm.open({
    schema: [TaskSchema],
    sync: {
      user: app.currentUser as Realm.User,
      partitionValue: "quickstart",
    },
  });

  // Get all Tasks in the realm
  const tasks: Realm.Collection<Task> = realm.objects<Task>("Task");

  // Add a listener that fires whenever one or more Tasks are inserted, modified, or deleted.
  tasks.addListener(taskListener);

  // Add a couple of Tasks in a single, atomic transaction
  // Realm automatically sets the _partition property based on the partitionValue used to open the realm
  realm.write(() => {
    const task1: Task = realm.create("Task", {
      _id: new ObjectId(),
      name: "go grocery shopping",
      status: "Open",
    });

    const task2 = realm.create("Task", {
      _id: new ObjectId(),
      name: "go exercise",
      status: "Open",
    });
    console.log(`created two tasks: ${task1.name} & ${task2.name}`);
  });

  // Find a specific Task
  let task: Task = tasks.filtered("status = 'Open' LIMIT(1)")[0];
  console.log("task", JSON.stringify(task, null, 2));

  // Update the Task
  realm.write(() => {
    task.status = "InProgress";
  });

  // Delete the Task
  realm.write(() => {
    realm.delete(task);
  });

  // Clean up
  tasks.removeListener(taskListener);
  realm.close();
  app.currentUser?.logOut();
}
run().catch((err) => {
  console.error(err);
});

// Define the collection notification listener
const taskListener: Realm.CollectionChangeCallback<Task> = (
  tasks: Realm.Collection<Task>,
  changes: Realm.ObjectChanges
) => {
  // Update UI in response to deleted objects
  (changes.deletions as unknown as number[]).forEach((index) => {
    // Deleted objects cannot be accessed directly,
    // but we can update a UI list, etc. knowing the index.
    console.log(`- deleted a task -`);
  });

  // Update UI in response to inserted objects
  (changes.insertions as unknown as number[]).forEach((index) => {
    let insertedTask = tasks[index].name;
    console.log(`inserted task: ${JSON.stringify(insertedTask, null, 2)}`);
    // ...
  });

  // Update UI in response to modified objects
  (changes.newModifications as unknown as number[]).forEach((index) => {
    let modifiedTask = tasks[index];
    console.log(`modified task: ${JSON.stringify(modifiedTask, null, 2)}`);
    // ...
  });
};
const Realm = require("realm");
const BSON = require("bson");

// Update this with your App ID
const app = new Realm.App({ id: "<Your App ID>" });
const TaskSchema = {
  name: "Task",
  properties: {
    _id: "objectId",
    _partition: "string?",
    name: "string",
    status: "string",
  },
  primaryKey: "_id",
};

async function run() {
  const credentials = Realm.Credentials.anonymous();
  await app.logIn(credentials);
  console.log(`Logged in anonymously with user id: ${app.currentUser.id}`);

  const realm = await Realm.open({
    schema: [TaskSchema],
    sync: {
      user: app.currentUser,
      partitionValue: "quickstart",
    },
  });

  // Get all Tasks in the realm
  const tasks = realm.objects("Task");

  // Add a listener that fires whenever one or more Tasks are inserted, modified, or deleted.
  tasks.addListener(taskListener);

  // Add a couple of Tasks in a single, atomic transaction
  // Realm automatically sets the _partition property based on the partitionValue used to open the realm
  realm.write(() => {
    const task1 = realm.create("Task", {
      _id: new BSON.ObjectID(),
      name: "go grocery shopping",
      status: "Open",
    });
    
    const task2 = realm.create("Task", {
      _id: new BSON.ObjectID(),
      name: "go exercise",
      status: "Open",
    });
    console.log(`created two tasks: ${task1.name} & ${task2.name}`);
  });

  // Find a specific Task
  let task = tasks.filtered("status = 'Open' LIMIT(1)")[0];
  console.log("task", JSON.stringify(task, null, 2));

  // Update the Task
  realm.write(() => {
    task.status = "InProgress";
  });

  // Delete the Task
  realm.write(() => {
    realm.delete(task);
    task = null;
  });

  // Clean up
  tasks.removeListener(taskListener);
  realm.close();
  app.currentUser.logOut();
}
run().catch(err => {
  console.error(err)
});

// Define the collection notification listener
function taskListener(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(`- deleted a task -`);
  });

  // Update UI in response to inserted objects
  changes.insertions.forEach((index) => {
    let insertedTask = tasks[index].name;
    console.log(`inserted task: ${JSON.stringify(insertedTask, null, 2)}`);
    // ...
  });

  // Update UI in response to modified objects
  changes.newModifications.forEach((index) => {
    let modifiedTask = tasks[index];
    console.log(`modified task: ${JSON.stringify(modifiedTask, null, 2)}`);
    // ...
  });
}

Output

Running the above code should output something like the following:

Logged in anonymously with user id: 5f1f9fb75512f2cb670ad033
Connection[1]: Session[1]: client_reset_config = false, Realm exists = false, async open = false, client reset = false
Connection[1]: Connected to endpoint '75.2.1.110:443' (from '192.168.1.154:60136')
created two tasks: go grocery shopping & go exercise
task {
  "_id": "5f1f9fb70a74d46af33c7a02",
  "_partition": null,
  "name": "go grocery shopping",
  "status": "Open"
}

inserted task: "go grocery shopping"

inserted task: "go exercise"

modified task: {
  "_id": "5f1f9fb70a74d46af33c7a02",
  "_partition": null,
  "name": "go grocery shopping",
  "status": "InProgress"
}
Connection[1]: Disconnected