Navigation

Quick Start

Overview

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

Check Out the Tutorial

This page contains only the essential information that you need to set up a MongoDB Realm application. If you prefer to follow a guided tutorial that shows you step-by-step how to set up a working app, check out the React Native Tutorial where you’ll build a mobile app that connects to the Task Tracker backend.

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 Realm from '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.

import Realm from 'realm';

// Returns the shared instance of the Realm app.
export function getRealmApp() {
   const appId = '<enter your Realm app ID here>'; // Set Realm app ID here.
   const appConfig = {
     id: appId,
     timeout: 10000,
   };
  return new Realm.App(appConfig);
}

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.

import {ObjectId} from 'bson';

class Task {
  constructor({
    name,
    partition,
    status = Task.STATUS_OPEN,
    id = new ObjectId(),
  }) {
    this._partition = partition;
    this._id = id;
    this.name = name;
    this.status = status;
  }

  static STATUS_OPEN = 'Open';
  static STATUS_IN_PROGRESS = 'InProgress';
  static STATUS_COMPLETE = 'Complete';

  static schema = {
    name: 'Task',
    properties: {
      _id: 'objectId',
      _partition: 'string',
      name: 'string',
      status: 'string',
    },
    primaryKey: '_id',
  };
}

export {Task};

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:

import Realm from 'realm';

async function anonymousLogin() {
  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);
    return user;

  } catch (error) {
      throw `Error logging in anonymously: ${JSON.stringify(error,null,2)}`;
  }
}

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:

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

    realm = await Realm.open(config);
  } catch (error) {
      throw `Error opening realm: ${JSON.stringify(error,null,2)}`;
  }
}

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", {
    _id: new ObjectId(),
    name: "go grocery shopping",
    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:

let filteredTasks = tasks.filtered("status = 'Open');
console.log(`filtered tasks: ${JSON.stringify(filteredTasks, null, 2)}\n`);

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.

export function watch(realm) {
  // 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.
  return 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();