Navigation

Quick Start

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

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";

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>" });

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

Info With Circle IconCreated with Sketch.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',
};

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.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}`);
};
handleLogin().catch(err => {
console.error("Failed to log in:", err)
});
Bulb IconTip
See Also:

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 = await Realm.open({
schema: [TaskSchema],
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)
});
Bulb IconTip
See Also:

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

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 = realm.create<Task>("Task", {
_id: new BSON.ObjectID(),
name: "go grocery shopping",
status: "Open",
});
});

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.objects<Task>("Task");

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

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

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

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

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

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

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 = ( 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);

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);

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

app.currentUser?.logOut();

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 = await Realm.open({
schema: [TaskSchema],
sync: {
user: app.currentUser as Realm.User,
partitionValue: "quickstart",
},
});
// Get all Tasks in the realm
const tasks = 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 = realm.create<Task>("Task", {
_id: new ObjectId(),
name: "go grocery shopping",
status: "Open",
});
const task2 = realm.create<Task>("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 = ( 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)}`);
// ...
});
};

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
Give Feedback