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.

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 appId = "<your-realm-app-id>"; // replace this with your App ID
const appConfig = {
  id: appId,
  timeout: 10000,
};

Define Your Object Model

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

Note

If you have enabled Sync but turned off Developer 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 Developer Mode if you want to make changes to the object model definition from client-side code. See Configure Your Data Model.

const TaskModel = {
  name: "Task",
  properties: {
    _id: "object id",
    _partition: "string",
    name: "string",
    status: "string",
  },
  primaryKey: "_id",
};

Authenticate a User

When you have enabled anonymous authentication in the Realm UI, users can immediately log into your app without providing any identifying information:

async function run() {
  let user;
  try {
    const app = new Realm.App(appConfig); // pass in the appConfig variable that you created earlier

    const credentials = Realm.Credentials.anonymous(); // create an anonymous credential
    user = await app.logIn(credentials);

    console.log(`Logged in with the user: ${user.identity}`);
  } finally {
    // ...
  }
}
run().catch(console.dir);

Realm provides many additional ways to authenticate, register, and link users.

Open a Realm

Once you have enabled Realm Sync and authenticated a user, you can open a synced realm:

async function run() {
  let user;
  let realm;
  try {
    // ...
    console.log(`Logged in with the user: ${user.identity}`);
    const config = {
      schema: [TaskModel],
      sync: {
        user: user,
        partitionValue: '"myPartition"',
      },
    };

    realm = await Realm.open(config);
  } finally {
    // ...
  }
}
run().catch(console.dir);

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.

To create a new Task run the method “realm.create()” inside the “realm.write()” callback. Pass the string “Task” as the first parameter to “realm.create()”. Pass a Task object as the second parameter.

realm.write(() => {
  realm.create("Task", {
    name: "buy milk, eggs, and bread",
    status: "Open",
  });
});

You can retrieve a live collection of all tasks in the realm:

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

You can also filter that collection using a filter:

console.log(`Number of complete tasks: ${tasks.filtered("complete = true")}`);

To modify a task, update its properties in a write transaction block:

realm.write(() => {
  task.status = 'InProgress';
});

Finally, you can delete a task:

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

  // Discard the reference.
  task = null;
});

Watch for Changes

You can watch a realm, collection, or object for changes by adding a listener event handler with the “addListener()” method.

// 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
  changes.modifications.forEach((index) => {
    let modifiedTask = tasks[index];
    // ...
  });
}

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

To stop watching for changes, run the “realm.removeAllListeners()” method. Alternatively, to remove a specific listener, call “removeListener()” on the object that is being watched and pass in the listener function:

// Unregister all listeners
realm.removeAllListeners();

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

Log Out

Once logged in, you can log out:

user.logOut();

Complete Example

Run the complete example, by replacing the appId with your realm app ID.

const Realm = require("realm");

const appId = "<your-realm-app-id>"; // replace this with your App ID
const appConfig = {
  id: appId,
  timeout: 10000,
};
const TaskModel = {
  name: "Task",
  primaryKey: "_id",
  properties: {
    _id: "object id?",
    name: "string",
    description: "string",
  },
};

// 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
  changes.modifications.forEach((index) => {
    let modifiedTask = tasks[index];
    // ...
  });
}

async function run() {
  let user;
  let realm;
  let tasks;
  try {
    const app = new Realm.App(appConfig);

    const credentials = Realm.Credentials.anonymous(); // create an anonymous credential

    user = await app.logIn(credentials);

    const config = {
      schema: [TaskModel],
      sync: {
        user: user,
        partitionValue: "myPartition",
      },
    };

    realm = await Realm.open(config);

    console.log(`Logged in with the user: ${user.identity}`);

    realm.write(() => {
      realm.create("Task", {
        name: "buy milk, eggs, and bread",
        status: "Open",
      });
    });

    tasks = realm.objects("Task");

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

    console.log(`Number of complete tasks: ${tasks.filtered("complete = true")}`);

    realm.write(() => {
      task.status = "InProgress";
    });

    realm.write(() => {
      // Delete the task from the realm.
      realm.delete(task);
      // Discard the reference.
      task = null;
    });
  } finally {
    user.logOut();
    tasks.removeListener(listener);
    realm.close();
  }
}
run().catch(console.dir);