Getting Started
Installation
Follow the installation instructions below to install Realm JavaScript via npm, or see the source on GitHub.
Prerequisites
- Make sure your environment is set up to run React Native applications. Follow the React Native instructions for getting started.
- Apps using Realm can target both iOS and Android.
- React Native 0.31.0 and later is supported.
Installation
-
Create a new React Native project:
react-native init <project-name>
-
Change directories into the new project (
cd <project-name>
) and add therealm
dependency:npm install --save realm
-
Next, link your project to the
realm
native module.react-native link realm
Warning for Android: Depending on the version, react-native link
may generate an invalid configuration, updating Gradle correctly (android/settings.gradle
and android/app/build.gradle
) but failing to add the Realm module. Confirm that react-native link
has added the Realm module; if it has not, link manually to the library with the following steps:
-
Add the following lines to
android/settings.gradle
:include ':realm' project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')
-
Add Realm to dependencies in
android/app/build.gradle
:// When using Android Gradle plugin 3.0 or higher dependencies { implementation project(':realm') } // When using Android Gradle plugin lower than 3.0 dependencies { compile project(':realm') }
-
Add the import and link the package in
MainApplication.java
:import io.realm.react.RealmReactPackage; // add this import public class MainApplication extends Application implements ReactApplication { @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RealmReactPackage() // add this line ); } }
You’re now ready to go. To see Realm in action, replace the definition of class <project-name>
with the following in App.js
:
const Realm = require('realm');
class <project-name> extends Component {
constructor(props) {
super(props);
this.state = { realm: null };
}
componentWillMount() {
Realm.open({
schema: [{name: 'Dog', properties: {name: 'string'}}]
}).then(realm => {
realm.write(() => {
realm.create('Dog', {name: 'Rex'});
});
this.setState({ realm });
});
}
render() {
const info = this.state.realm
? 'Number of dogs in this Realm: ' + this.state.realm.objects('Dog').length
: 'Loading...';
return (
<View style={styles.container}>
<Text style={styles.welcome}>
{info}
</Text>
</View>
);
}
}
You can then run your app on a device and in a simulator.
Please note that Expo does not support Realm, create-react-native-app
will not work.
Prerequisites
- Node 6, 8, and 10 are supported.
- Linux, macOS, and Windows 8 (and later) are supported.
Installation
To install Realm Node.js, simply use the Node Package Manager:
npm install --save realm
To use the SDK, require('realm')
in your application.
var Realm = require('realm');
Introduction
Realm JavaScript enables you to efficiently write your app’s model layer in a safe, persisted and fast way. It’s designed to work with React Native and Node.js.
Here’s a quick example:
const Realm = require('realm');
// Define your models and their properties
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: 'Car[]',
picture: 'data?' // optional property
}
};
Realm.open({schema: [CarSchema, PersonSchema]})
.then(realm => {
// Create Realm objects and write to local storage
realm.write(() => {
const myCar = realm.create('Car', {
make: 'Honda',
model: 'Civic',
miles: 1000,
});
myCar.miles += 20; // Update a property value
});
// Query Realm for all cars with a high mileage
const cars = realm.objects('Car').filtered('miles > 1000');
// Will return a Results object with our 1 car
cars.length // => 1
// Add another car
realm.write(() => {
const myCar = realm.create('Car', {
make: 'Ford',
model: 'Focus',
miles: 2000,
});
});
// Query results are updated in realtime
cars.length // => 2
})
.catch(error => {
console.log(error);
});
Note that if you are going to use Realm for server-side/node, there is additional information to be found in the Realm Object Server documentation.
Realm Studio
Realm Studio is our premiere developer tool, built so you can easily manage the Realm Database and Realm Platform. With Realm Studio, you can open and edit local and synced Realms, and administer any Realm Object Server instance. It supports Mac, Windows and Linux.
Realms
Opening Realms
Opening a Realm is simply performed by calling the static open
method on the Realm
class. Pass a configuration object. We’ve seen this used already in examples with a configuration object that includes the schema
key:
// Get the default Realm with support for our objects
Realm.open({schema: [Car, Person]})
.then(realm => {
// ...use the realm instance here
})
.catch(error => {
// Handle the error here if something went wrong
});
For full details about the configuration object, see the API Reference for configuration. Some of the more common keys for the object, beyond schema
, include:
path
: specify a path to another Realmmigration
: a migration functionsync
: a sync object, to open a Realm synchronized with the Realm Object ServerinMemory
: the Realm will be opened in-memory, and objects are not persisted; once the last Realm instance is closed, all objects vanishdeleteRealmIfMigrationNeeded
: delete the Realm if migration is needed; this is useful under development since the data model might change often
The Default Realm
You may have noticed in all previous examples that the path argument has been omitted. In this case the default Realm path is used. You can access and change the default Realm path using the Realm.defaultPath
global property.
Opening a Synchronized Realm
Are you looking to use Realm Mobile Platform to synchronize all of your Realm Databases? All sync related documentation has been moved to our platform documentation
Other Realms
It’s sometimes useful to have multiple Realms persisted at different locations. For example, you may want to bundle some data with your application in a Realm file, in addition to your main Realm. You can do this by specifying the path
argument when initializing your realm. All paths are relative to the writable documents directory for your application:
// Open a realm at another path
Realm.open({
path: 'anotherRealm.realm',
schema: [CarSchema]
}).then(/* ... */);
Schema Version
Another option available when opening a Realm is the schemaVersion
property. When omitted, the schemaVersion
property defaults to 0
. You are required to specify the schemaVersion
when initializing an existing Realm with a schema that contains objects that differ from their previous specification. If the schema was updated and the schemaVersion
was not, an exception will be thrown.
const PersonSchema = {
name: 'Person',
properties: {
name: 'string'
}
};
// schemaVersion defaults to 0
Realm.open({schema: [PersonSchema]});
If you then later do something like this:
const UpdatedPersonSchema = {
// The schema name is the same, so previous `Person` object
// in the Realm will be updated
name: 'Person',
properties: {
name: 'string',
dog: 'Dog' // new property
}
};
// this will throw because the schema has changed
// and `schemaVersion` is not specified
Realm.open({schema: [UpdatedPersonSchema]});
// this will succeed and update the Realm to the new schema
Realm.open({schema: [UpdatedPersonSchema], schemaVersion: 1});
If you wish to retrieve the current schema version of a Realm, you may do so with the Realm.schemaVersion
method.
const currentVersion = Realm.schemaVersion(Realm.defaultPath);
Synchronously Opening Realms
You can create a realm instance by simply invoking the constructor and passing a configuration object to it. This is typically not recommended as it blocks and could potentially be a time consuming operation, especially if there are migrations to run or if the realm is synchronized and you don’t want to risk modifying data before it’s been completely downloaded.
If you still want to do this, the pattern is simple:
const realm = new Realm({schema: [PersonSchema]});
// You can now access the realm instance.
realm.write(/* ... */);
Models
Realm data models are defined by the schema information passed into a Realm during initialization. The schema for an object consists of the object’s name
and a set of properties. Each property has a name and is described by either a string containing the property’s type, or an object with name
, type
, objectType
, optional
, default
, and indexed
fields.
const Realm = require('realm');
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: 'Car[]'
picture: 'data?', // optional property
}
};
// Initialize a Realm with Car and Person models
Realm.open({schema: [CarSchema, PersonSchema]})
.then(realm => {
// ... use the realm instance to read and modify data
})
Classes
At this point, support for defining models via classes is limited. It works in React Native but not in Node.
If you want to use ES2015 classes (and maybe want to inherit existing features), you just need to define the schema on the constructor:
class Person {
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
Person.schema = {
name: 'Person',
properties: {
firstName: 'string',
lastName: 'string'
}
};
You can now pass the class itself to the schema
property of the open configuration:
Realm.open({schema: [Person]})
.then( /* ... */ );
You access properties as always:
realm.write(() => {
const john = realm.create('Person', {
firstName: 'John',
lastName: 'Smith'
});
john.lastName = 'Peterson';
console.log(john.fullName); // -> 'John Peterson'
});
Supported types
Realm supports the following basic types: bool
, int
, float
, double
, string
, data
, and date
.
bool
properties map to JavaScriptboolean
valuesint
,float
, anddouble
properties map to JavaScriptnumber
values. Internally ‘int’ and ‘double’ are stored as 64 bits whilefloat
is stored with 32 bits.string
properties map tostring
data
properties map toArrayBuffer
date
properties map toDate
When specifying basic properties as a shorthand you may specify only the type rather than having to specify a dictionary with a single entry:
const CarSchema = {
name: 'Car',
properties: {
// The following property types are equivalent
make: {type: 'string'},
model: 'string',
}
}
Optional Properties
By default, basic types are non-optional and do not support storing null
or undefined
. Properties can be made optional by specifying the optional
designator in your property definition, or with the shorthand syntax, by appending a ?
to the type name:
const PersonSchema = {
name: 'Person',
properties: {
realName: 'string', // required property
displayName: 'string?', // optional property
birthday: {type: 'date', optional: true}, // optional property
}
};
let realm = new Realm({schema: [PersonSchema, CarSchema]});
realm.write(() => {
// optional properties can be set to null or undefined at creation
let charlie = realm.create('Person', {
realName: 'Charlie',
displayName: null, // could also be omitted entirely
birthday: new Date(1995, 11, 25),
});
// optional properties can be set to `null`, `undefined`,
// or to a new non-null value
charlie.birthday = undefined;
charlie.displayName = 'Charles';
// Setting a non-optional property to null will throw `TypeError`
// charlie.realName = null;
});
List Properties
In addition to storing individual values, properties can also be declared as a list of any of the supported basic types. This is done by appending []
to the type name:
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
testScores: 'double?[]'
}
};
let realm = new Realm({schema: [PersonSchema, CarSchema]});
realm.write(() => {
let charlie = realm.create('Person', {
name: 'Charlie',
testScores: [100.0]
});
// Charlie had an excused absense for the second test and was allowed to skip it
charlie.testScores.push(null);
// And then he didn't do so well on the third test
charlie.testScores.push(70.0);
});
When accessing list properties a List
object is returned. List
has methods very similar to a regular JavaScript array. The big difference is that any changes made to a List
are automatically persisted to the underlying Realm, and as such they can only be modified in write transactions. Additionally, List
s belong to the underlying object they were acquired from - you can only get List
instances by accessing a property from an owning object and they cannot be manually created.
While the values in a list property can be made optional, the list property itself cannot be. Specifying a list property as optional
using the longhand syntax (values: {type: 'int[]', optional: true}
) will make the values within the list optional.
Relationships
To-One Relationships
For to-one relationships you specify the name
property of the object schema you are referencing as the property’s type:
const PersonSchema = {
name: 'Person',
properties: {
// The following property definitions are equivalent
car: {type: 'Car'},
van: 'Car',
}
};
When using object properties you need to make sure all referenced types are present in the schema used to open the Realm:
// CarSchema is needed since PersonSchema contains properties of type 'Car'
Realm.open({schema: [CarSchema, PersonSchema]})
.then(/* ... */);
When accessing object properties, you can access nested properties using normal property syntax:
realm.write(() => {
const nameString = person.car.name;
person.car.miles = 1100;
// create a new Car by setting the property to an object
// with all of the required fields
person.van = {make: 'Ford', model: 'Transit'};
// set both properties to the same car instance
person.car = person.van;
});
Object properties in Realm are always optional, do not have to be explicitly specified as such, and cannot be made required.
To-Many Relationships
Just as with basic properties, you can also have a list of objects to form a to-many relationship. This is done by either appending []
to the name of the target object schema, or by setting the property type to list
and specifying the objectType
:
const PersonSchema = {
name: 'Person',
properties: {
// The following property definitions are equivalent
cars: {type: 'list', objectType: 'Car'},
vans: 'Car[]'
}
}
let carList = person.cars;
// Add new cars to the list
realm.write(() => {
carList.push({make: 'Honda', model: 'Accord', miles: 100});
carList.push({make: 'Toyota', model: 'Prius', miles: 200});
});
let secondCar = carList[1].model; // access using an array index
Unlike other lists and to-one relationships, to-many relationships cannot be made optional.
Inverse Relationships
Links are unidirectional. So if a to-many property Person.dogs
links to Dog
instances and a to-one property Dog.owner
links to Person
, these links are independent from one another. Appending a Dog
to a Person
instance’s dogs
property doesn’t automatically set the dog’s owner
property to this Person
. Because manually synchronizing pairs of relationships is error prone, complex and duplicates information, Realm provides linking objects properties to represent these inverse relationships.
With linking objects properties, you can obtain all objects that link to a given object from a specific property. For example, a Dog
object can have a property named owners
that contains all of the Person
objects that have this exact Dog
object in their dogs
property. This is done by making the owners
property of type linkingObjects
and then specifying the relationship that it has with the Person
object.
const PersonSchema = {
name: 'Person',
properties: {
dogs: 'Dog[]'
}
}
const DogSchema = {
name:'Dog',
properties: {
// No shorthand syntax for linkingObjects properties
owners: {type: 'linkingObjects', objectType: 'Person', property: 'dogs'}
}
}
A linkingObjects
property can point either to a List
property (to-many relationship) or an Object
property (to-one relationship):
const ShipSchema = {
name: 'Ship',
properties: {
captain: 'Captain'
}
}
const CaptainSchema = {
name: 'Captain',
properties: {
ships: {type: 'linkingObjects', objectType: 'Ship', property: 'captain'}
}
}
When accessing linkingObjects
properties, a Results
object is returned, so further querying and sorting are fully supported. linkingObject
properties belong to the object they were acquired from and can not be set or manipulated directly. They are updated automatically when a transaction is committed.
Accessing linkingObjects
without a schema: if you have opened a Realm file without specifying a schema, e.g. in a Realm Functions callback, you can get a linkingObjects
property by calling linkingObjects(objectType, property)
on an Object
instance:
let captain = realm.objectForPrimaryKey('Captain', 1);
let ships = captain.linkingObjects('Ship', 'captain');
Linking objects properties cannot be made optional.
Default Property Values
Default property values can be specified by setting the default
designator in the property definition. To use a default value, leave the property unspecified during object creation.
const CarSchema = {
name: 'Car',
properties: {
make: {type: 'string'},
model: {type: 'string'},
drive: {type: 'string', default: 'fwd'},
miles: {type: 'int', default: 0}
}
};
realm.write(() => {
// Since `miles` is left out it defaults to `0`, and since
// `drive` is specified, it overrides the default value
realm.create('Car', {make: 'Honda', model: 'Accord', drive: 'awd'});
});
Indexed Properties
You can add an indexed
designator to a property definition to cause that property to be indexed. This is supported for int
, string
, bool
, and date
property types:
var BookSchema = {
name: 'Book',
properties: {
name: { type: 'string', indexed: true },
price: 'float'
}
};
Indexing a property will greatly speed up queries where the property is compared for equality at the cost of slower insertions.
Primary Keys
You can specify the primaryKey
property in an object model for string
and int
properties. Declaring a primary key allows objects to be looked up and updated efficiently and enforces uniqueness for each value. Once an object with a primary key has been added to a Realm the primary key cannot be changed.
const BookSchema = {
name: 'Book',
primaryKey: 'id',
properties: {
id: 'int', // primary key
title: 'string',
price: 'float'
}
};
Primary key properties are automatically indexed.
Writes
Changes to objects in a Realm—creating, updating and deleting—must take place within a write()
transaction block. Note that write transactions have a non-negligible overhead; you should try to minimize the number of write
blocks within your code.
Creating Objects
Objects are created using the create
method:
try {
realm.write(() => {
realm.create('Car', {make: 'Honda', model: 'Accord', drive: 'awd'});
});
} catch (e) {
console.log("Error on creation");
}
Note that any exceptions thrown in write()
will cancel the transaction. The try/catch
block won’t be shown in all examples, but it’s good practice.
Nested Objects
If an object has object properties, values for those properties can be created recursively by specifying JSON values for each child property:
realm.write(() => {
realm.create('Person', {
name: 'Joe',
// nested objects are created recursively
car: {make: 'Honda', model: 'Accord', drive: 'awd'},
});
});
Updating Objects
Typed Updates
You can update any object by setting its properties within a write transaction.
realm.write(() => {
car.miles = 1100;
});
Creating and Updating Objects With Primary Keys
If your model class includes a primary key, you can have Realm intelligently update or add objects based off of their primary key values. This is done by passing true
as the third argument to the create
method:
realm.write(() => {
// Create a book object
realm.create('Book', {id: 1, title: 'Recipes', price: 35});
// Update book with new price keyed off the id
realm.create('Book', {id: 1, price: 55}, true);
});
In the example above, since an object already exists with the id
value of 1
and we have passed in true
for the third argument, the price property is updated rather than trying to create a new object. Since the title
property is omitted the object retains the original value for this property. Note that when creating or updating objects with primary key properties the primary key must be specified.
Deleting Objects
Objects can be deleted by calling the delete
method within a write transaction.
realm.write(() => {
// Create a book object
let book = realm.create('Book', {id: 1, title: 'Recipes', price: 35});
// Delete the book
realm.delete(book);
// Delete multiple books by passing in a `Results`, `List`,
// or JavaScript `Array`
let allBooks = realm.objects('Book');
realm.delete(allBooks); // Deletes all books
});
Queries
Queries allow you to get objects of a single type from a Realm, with the option of filtering and sorting those results. All queries (including queries and property access) are lazy in Realm. Data is only read when objects and properties are accessed. This allows you to represent large sets of data in a performant way.
When performing queries you are returned a Results
object. Results are simply a view of your data and are not mutable.
The most basic method for retrieving objects from a Realm is using the objects
method on a Realm
to get all objects of a given type:
let dogs = realm.objects('Dog'); // retrieves all Dogs from the Realm
Filtering
You can get a filtered Results
by calling the filtered
method on a List
or a Results
with a query string.
For example, the following would change our earlier example to retrieve all dogs with the color tan and names beginning with ‘B’:
let dogs = realm.objects('Dog');
let tanDogs = dogs.filtered('color = "tan" AND name BEGINSWITH "B"');
The query language supported by Realm is inspired by Apple’s NSPredicate. Let’s briefly summarize the supported features and syntax:
- The comparison operands can be property names or constants. At least one of the operands must be a property name. Special constants are
false
,true
, andnull
. - Timestamps can be specified in the formats
YYYY-MM-DD@HH:MM:SS:NANOSECONDS
andYYYY-MM-DDTHH:MM:SS:NANOSECONDS
where nanoseconds can be omitted. - The comparison operators
=
/==
,<=
,<
,>=
,>
, and!=
/<>
are supported forint
,float
,double
, andDate
property types, e.g.age = 45
. - The comparison operators
=
/==
and!=
/<>
are supported for boolean (bool
) properties. - For string and data (
ArrayBuffer
) properties, the=
(and==
),!=
(and<>
),BEGINSWITH
,CONTAINS
, andENDSWITH
operators are supported, e.g.name CONTAINS 'Ja'
. - Wildcard comparison is possible for strings with the
LIKE
operator, e.g.name LIKE '*an?'
to match “Jane”, “Dan”, “Shane”, etc. - Case-insensitive comparisons for strings using
[c]
, e.g. ,CONTAINS[c] 'Ja'
. Note that only characters “A-Z” and “a-z” will be ignored for case. - Realm supports the following compound operators:
AND
/&&
,OR
/||
, andNOT
/!
, e.g.name BEGINSWITH 'J' AND age >= 32
. - The aggregate expressions
@count
/@size
,@min
,@max
,@sum
and@avg
are supported on list properties, e.g.employees.@count > 5
to find list of employees with more that 5 elements. - The aggregate expression
@count
/@size
on strings and binary properties, e.g.name.@size = 5
to find all with a name of 5 letters. - A key path can follow list properties relationships, e.g.
child.age >= 13
andcars.@avg.milage > 1000
. - A key path can also follow linking objects (backlinks), e.g.
parents.age > 25
andparents.@count == 2
. - The
$
operator can be used to substitute arguments, e.g.child.age >= $0
(see the example below). - Sorting and find distinct values are possible with functions
SORT
andDISTINCT
, e.g.age > 20 SORT(name ASC, age DESC) DISTINCT(name)
.- The ordering for sorting can be one of the following case insensitive literals:
ASC
,ASCENDING
,DESC
,DESCENDING
. - Any number of properties can appear inside the brackets in a comma separated list.
- Any number of sort/distinct conditions can be indicated, they will be applied in the specified order.
- Sort or distinct cannot operate independently, these conditions must be attached to at least one query filter.
- The ordering for sorting can be one of the following case insensitive literals:
An non-trivial example on how to query a Realm is:
const Realm = require('realm');
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
cars: {type: 'list', objectType: 'Car'},
}
};
// Initialize a Realm with Car and Person models
Realm.open({schema: [CarSchema, PersonSchema]})
.then(realm => {
// Add persons and their cars
realm.write(() => {
let john = realm.create('Person', {name: 'John', cars: []});
john.cars.push({make: 'Honda', model: 'Accord', miles: 1500});
john.cars.push({make: 'Toyota', model: 'Prius', miles: 2780});
let joan = realm.create('Person', {name: 'Joan', cars: []});
joan.cars.push({make: 'Skoda', model: 'Octavia', miles: 1120});
joan.cars.push({make: 'Ford', model: 'Fiesta', miles: 95});
joan.cars.push({make: 'VW', model: 'Golf', miles: 1270});
let jill = realm.create('Person', {name: 'Jill', cars: []});
let jack = realm.create('Person', {name: 'Jack', cars: []});
jack.cars.push({make: 'Porche', model: '911', miles: 965});
});
// Find car owners
let carOwners = realm.objects('Person').filtered('cars.@size > 0');
console.log('Car owners')
for (let p of carOwners) {
console.log(` ${p.name}`);
}
// Find who has been driver longer than average
let average = realm.objects('Car').avg('miles');
let longerThanAverage = realm.objects('Person').filtered('cars.@sum.miles > $0', average);
console.log(`Longer than average (${average})`)
for (let p of longerThanAverage) {
console.log(` ${p.name}: ${p.cars.sum('miles')}`);
}
realm.close();
});
The output of the code snippet is:
Car owners
John
Joan
Jack
Longer than average (1288.3333333333333)
John: 4280
Joan: 2485
Sorting
Results
allows you to specify a sort criteria and order based on a single or multiple properties. For example, the following call sorts the returned cars from the example above numerically by miles:
let hondas = realm.objects('Car').filtered('make = "Honda"');
// Sort Hondas by mileage
let sortedHondas = hondas.sorted('miles');
// Sort in descending order instead
sortedHondas = hondas.sorted('miles', true);
// Sort by price in descending order and then miles in ascending
sortedHondas = hondas.sorted([['price', true], ['miles', false]]);
Results
can also be sorted on the values of objects linked to by the objects you’re sorting:
let people = realm.objects('Person');
// Sort people by the milage of their cars
let sortedPeople = people.sorted('car.miles');
List
s of basic types can be sorted by their values by calling sorted()
without specifying a property:
let person = realm.objects('Person')[0];
let sortedTestScores = person.testScores.sorted();
Note that the order of Results
is only guaranteed to stay consistent when the query is sorted. For performance reasons, insertion order is not guaranteed to be preserved.
Auto-Updating Results
Results
instances are live, auto-updating views into the underlying data, which means results never have to be re-fetched. Modifying objects that affect the query will be reflected in the results immediately. The one exception to this is when using for...in
or for...of
, which will always iterate over the objects which matched the query when the iteration is started, even if some of them are deleted or modified to be excluded by the filter during the iteration.
let hondas = realm.objects('Car').filtered('make = "Honda"');
// hondas.length == 0
realm.write(() => {
realm.create('Car', {make: 'Honda', model: 'RSX'});
});
// hondas.length == 1
This applies to all Results
instances, included those returned by the objects
, filtered
, and sorted
methods.
This property of Results
not only keeps Realm fast and efficient, it allows your code to be simpler and more reactive. For example, if your view relies on the results of a query, you can store the Results
in a property and access it without having to make sure to refresh its data prior to each access.
You can subscribe to notifications to know when Realm data is updated, indicating when your app’s UI should be refreshed for example, without having to re-fetch your Results
.
Limiting Results
Most other database technologies provide the ability to ‘paginate’ results from queries (such as the ‘LIMIT’ keyword in SQLite). This is often done out of necessity to avoid reading too much from disk, or pulling too many results into memory at once.
Since queries in Realm are lazy, performing this sort of paginating behavior isn’t necessary at all, as Realm will only load objects from the results of the query once they are explicitly accessed.
If for UI-related or other implementation reasons you require a specific subset of objects from a query, it’s as simple as taking the Results
object, and reading out only the objects you need.
let cars = realm.objects('Car');
// get first 5 Car objects
let firstCars = cars.slice(0, 5);
Migrations
When working with a database your data model will most likely change over time. For example, suppose we have the following Person
model:
const PersonSchema = {
name: 'Person',
properties: {
firstName: 'string',
lastName: 'string',
age: 'int'
}
}
We want to update the data model to require a name
property, rather than separate first and last names. To do this, we simply change the schema to the following:
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
age: 'int'
}
}
At this point if you had saved any data with the previous model version there will be a mismatch between the new code and the old data Realm has stored on disk. When this occurs, an exception will be thrown when you try to open the existing Realm with the new schema unless you run a migration.
Performing a Migration
You define a migration and the associated schema version by updating the schemaVersion and defining an optional migration
function. Your migration function provides any logic needed to convert data models from previous schemas to the new schema. When opening a Realm
the migration function will be applied to update the Realm
to the given schema version only if a migration is needed.
If no migration function is supplied then any new properties are automatically added and old properties are removed from the database when updating to the new schemaVersion
. If you need to update old or populate new properties when upgrading your version you can do this in the migration function. For example, suppose we want to migrate the Person
model declared earlier. You can populate the name
property of the new schema using the old firstName
and lastName
properties:
Realm.open({
schema: [PersonSchema],
schemaVersion: 1,
migration: (oldRealm, newRealm) => {
// only apply this change if upgrading to schemaVersion 1
if (oldRealm.schemaVersion < 1) {
const oldObjects = oldRealm.objects('Person');
const newObjects = newRealm.objects('Person');
// loop through all objects and set the name property in the new schema
for (let i = 0; i < oldObjects.length; i++) {
newObjects[i].name = oldObjects[i].firstName + ' ' + oldObjects[i].lastName;
}
}
}
}).then(realm => {
const fullName = realm.objects('Person')[0].name;
});
Once the migration is successfully completed the Realm and all of its objects can be accessed as usual by your app.
Linear Migrations
With the migration pattern described above you can potentially run into issues when migrating over multiple versions. This could happen if a user skips an app update and a property has been changed multiple times in the versions being skipped. In this case you may need to edit old migration code to correctly update data from old schema to the latest schema.
It’s possible to avoid this issue by running multiple migrations sequentially, making sure that the database is upgraded to each previous version and that the associated migration code is run. When following this pattern old migration code should never have to be modified, although you will need to keep all old schema and migration blocks for future use. An example of what this would look like:
const schemas = [
{ schema: schema1, schemaVersion: 1, migration: migrationFunction1 },
{ schema: schema2, schemaVersion: 2, migration: migrationFunction2 },
...
]
// the first schema to update to is the current schema version
// since the first schema in our array is at
let nextSchemaIndex = Realm.schemaVersion(Realm.defaultPath);
while (nextSchemaIndex < schemas.length) {
const migratedRealm = new Realm(schemas[nextSchemaIndex++]);
migratedRealm.close();
}
// open the Realm with the latest schema
Realm.open(schemas[schemas.length-1]);
Notifications
The Realm
, Results
and List
objects provide addListener
methods to register notification callbacks. Whenever the object is updated, the change notification callback will be called.
There are two kinds of notifications, “Realm Notifications” (simple callbacks notified when write transactions are committed) and “Collection Notifications” (more sophisticated callbacks which receive change metadata on insertions, deletions and updates).
In some cases the listener may be called when the transaction starts—if the Realm is advanced to the latest version, or Realm entities being observed were modified or deleted in a way that triggers notifications. In those cases, the listener runs within the context of the current write transaction, so an attempt to begin a new write transaction within the notification handler will throw an exception. You can use the Realm.isInTransaction
property to determine if your code is executing within a write transaction.
Realm Notifications
Realm instances send out notifications to other instances every time a write transaction is committed. To register for notifications:
function updateUI() {
// ...
}
// Observe Realm Notifications
realm.addListener('change', updateUI);
// ..later remove the listener
realm.removeListener('change', updateUI);
// ..or unregister all listeners
realm.removeAllListeners();
Collection Notifications
Collection notifications contain information that describe what changes have occurred at a fine-grained level. This consists of the indices of objects that have been inserted, deleted, or modified since the last notification. Collection notifications are delivered asynchronously: first with the initial results, and then after any write transaction which modifies any of the objects in the collection, deletes objects from the collection, or adds new objects to the collection.
The notification callback function given to addListener
receives two parameters when these changes occur. The first one is the collection that changed, and the second one is a changes
object with information about the collection indices affected by deletions, insertions and modifications.
The former two, deletions and insertions, record the indices whenever objects start and stop being part of the collection. This takes into account when you add objects to the Realm or delete them from the Realm. For Results
this also applies when you filter for specific values and the object was changed so that it is now matching the query or not matching anymore. For collections based on List
, this applies when objects are added or removed from the relationship.
Your application is notified about modifications whenever a property of an object has changed, which was previously part of the collection and is still part of it. This happens as well when to-one and to-many relationships change, but doesn’t take changes on inverse relationships into account.
class Dog {}
Dog.schema = {
name: 'Dog',
properties: {
name: 'string',
age: 'int',
}
};
class Person {}
Person.schema = {
name: 'Person',
properties: {
name: {type: 'string'},
dogs: {type: 'list', objectType: 'Dog'},
}
};
Let’s assume you’re observing a list of dog owners as given by the model code above. You will be notified about modifications for a matched Person
object when:
- You modify the
Person
’sname
property. - You add or remove a
Dog
to thePerson
’sdogs
property. - You modify the
age
property of aDog
belonging to thatPerson
.
This makes it possible to discretely control the animations and visual updates made to the content inside your UI, instead of arbitrarily reloading everything each time a notification occurs.
collectionListenerRetainer = realm.objects('Dog').filtered('age < 2');
// Observe Collection Notifications
function listener(puppies, changes) {
// Update UI in response to inserted objects
changes.insertions.forEach((index) => {
let insertedDog = puppies[index];
...
});
// Update UI in response to modified objects
changes.modifications.forEach((index) => {
let modifiedDog = puppies[index];
...
});
// Update UI in response to deleted objects
changes.deletions.forEach((index) => {
// Deleted objects cannot be accessed directly
// Support for accessing deleted objects coming soon...
...
});
});
collectionListenerRetainer.addListener(listener);
// Unregister all listeners
realm.removeAllListeners();
// OR Unregister this listener
collectionListenerRetainer.removeListener(listener);
Working with a Synchronized Realm
Are you looking to use Realm Mobile Platform to synchronize all of your Realm Databases? All sync related documentation has been moved to our platform documentation
Encryption
Please take note of the Export Compliance section of our LICENSE, as it places restrictions against the usage of Realm if you are located in countries with an export restriction or embargo from the United States.
Realm supports encrypting the database file on disk with AES-256+SHA2 by supplying a 64-byte encryption key when creating a Realm.
var key = new Int8Array(64); // pupulate with a secure key
Realm.open({schema: [CarObject], encryptionKey: key})
.then(realm => {
// Use the Realm as normal
var dogs = realm.objects('Car');
});
This makes it so that all of the data stored on disk is transparently encrypted and decrypted with AES-256 as needed, and verified with a SHA-2 HMAC. The same encryption key must be supplied every time you obtain a Realm instance.
There is a small performance hit (typically less than 10% slower) when using encrypted Realms.
Examples
Examples can be found on GitHub in the realm-js repository.
Note that on Android, you need the NDK installed and must have set the ANDROID_NDK
environment variable.
export ANDROID_NDK=/usr/local/Cellar/android-ndk/r10e
Troubleshooting
Missing Realm Constructor
If your app crashes, telling you that the Realm constructor was not found, there are a few things you can try:
First of all, run react-native link realm
If that doesn’t help, and your problem is on Android, try:
Add the following in your MainApplication.java
file: java import io.realm.react.RealmReactPackage;
And add the RealmReactPackage
to the list of packages:
protected List getPackages() {
return Arrays.asList(
new MainReactPackage(),
new RealmReactPackage() // add this line
);
}
add following two lines in settings.gradle
:
include ':realm'
project(':realm').projectDir = new File(settingsDir, '../node_modules/realm/android')
If your problem is on iOS, try: 1. Close all simulators/device builds 2. Stop the package manager running in terminal (or better yet, just restart terminal) 3. Open the ios folder in your app root in finder 4. Go into the build folder (note: you won’t see this build folder in atom, so just right click ios and click open in finder) 5. Delete everything inside of the build folder (just move to trash and keep trash around in case you’re worried) 6. Run react-native run-ios
to rebuild the whole thing
Chrome Debugging is slow
We are aware of this. The reason for this is that since Realm is written in C++ and runs native code, it has to run on the device/simulator. But given the zero-copy architecture, we need to send values in realm objects over the RPC wire every time you inspect an object that is stored in a Realm.
We are investigating various potential solutions for this problem. If you want to keep track of it, you can follow the GitHub issue.
Cannot download realm-sync-cocoa
We have seen a few reports where users are not able to build their app due to download problems. The symptome is that you see an error message like Error: unexpected end of file at Zlib.zlibOnError [as onerror] (zlib.js:142:17) errno: -5, code: 'Z_BUF_ERROR' }
.
It is possible to manually download the required files, and then build the app. The steps are:
- Locate to your project directory, and find
node_modules/realm/vendor/realm-ios
. It will be empty. - Create the file
download-realm.lock
using the following command:echo SYNC_SERVER_FOLDER=sync SYNC_ARCHIVE=realm-sync-cocoa-3.7.0.tar.gz SYNC_ARCHIVE_ROOT=core > download-realm.lock
. The version number (here 3.7.0) must match the Realm Sync version in the change log. - Locate to your downloaded file
realm-sync-cocoa-3.7.0.tar.gz
excute this commandtar -xzvf realm-sync-cocoa-3.7.0.tar.gz -C yourProjectDirectory/node_modules/realm/vendor/realm-ios
. - You will find the directory is not empty any more. Copy all the files under directory
core
and paste them under directoryyourProjectDirectory/node_modules/realm/vendor/realm-ios
.
Crash Reporting
We encourage you to use a crash reporter in your application. Many Realm operations could potentially fail at runtime (like any other disk IO), so collecting crash reports from your application will help identify areas where either you (or us) can improve error handling and fix crashing bugs.
Most commercial crash reporters have the option of collecting logs. We strongly encourage you to enable this feature. Realm logs metadata information (but no user data) when throwing exceptions and in irrecoverable situations, and these messages can help debug when things go wrong.
Getting help
- Professional Support We offer professional support for Realm Database and Realm Platform. If you have a support agreement, you can reach us via our support portal.
- Need help with your code? Ask on StackOverflow. We actively monitor & answer questions on SO!
- Have a bug to report? Open an issue on our repo. If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue.
- Have a feature request? Open an issue on our repo. Tell us what the feature should do, and why you want the feature.
- Love to follow what comes up next? Look at our changelog. The log shows the latest additions and changes we plan to release soon, and the history of how Realm has evolved.