Realm Database for JavaScript

20.2.0 · active · verified Wed Apr 22

Realm JS is an offline-first, mobile-optimized database designed for JavaScript environments including React Native, Node.js, and Electron. It provides direct access to data as native JavaScript objects, eliminating the need for ORMs and offering performance often surpassing raw SQLite operations. The current stable major version is v20.x, with v20.2.0 being a recent release. Realm maintains a frequent release cadence, often with minor updates and bug fixes. A key differentiator was its integration with MongoDB Atlas Device Sync, but this feature was officially deprecated and removed starting with v20.0.0. Developers now using `realm` (v20+) should treat it as a robust local-only database, with a separate `community` package available for the sync-less version.

Common errors

Warnings

Install

Imports

Quickstart

Initializes a Realm database, defines object schemas, performs write operations (creation and update), and queries existing data. It demonstrates basic CRUD.

import Realm from 'realm';

// Define your schema (object models)
class Car extends Realm.Object {
  static schema = {
    name: 'Car',
    properties: {
      make: 'string',
      model: 'string',
      miles: { type: 'int', default: 0 },
    },
  };
}

class Person extends Realm.Object {
  static schema = {
    name: 'Person',
    properties: {
      name: 'string',
      cars: 'Car[]', // Define a relationship
    },
  };
}

// Open a realm with the defined schemas
async function runRealmExample() {
  try {
    const realm = await Realm.open({
      path: 'myrealm.realm',
      schema: [Car, Person],
      schemaVersion: 1,
      // Exclude from iCloud backup, useful for app-specific data that can be re-downloaded
      excludeFromIcloudBackup: process.env.NODE_ENV === 'production' ? true : false,
    });

    // Write to the realm within a transaction
    realm.write(() => {
      const myCar = realm.create('Car', { make: 'Honda', model: 'Civic', miles: 1000 });
      realm.create('Person', { name: 'Alice', cars: [myCar] });
      realm.create('Car', { make: 'Toyota', model: 'Camry', miles: 5000 });
    });

    // Query objects
    const cars = realm.objects('Car');
    console.log(`Total cars in the realm: ${cars.length}`);
    const hondas = cars.filtered('make == "Honda"');
    console.log(`Number of Hondas: ${hondas.length}`);

    // Update an object
    realm.write(() => {
      const civic = hondas[0];
      if (civic) {
        civic.miles += 500;
      }
    });
    console.log(`Honda Civic miles after update: ${hondas[0]?.miles}`);

    // Remember to close the realm when done to release resources
    realm.close();
  } catch (error) {
    console.error("Error opening or interacting with Realm:", error);
  }
}

runRealmExample();

view raw JSON →