Define a Realm Object Schema - React Native SDK
On this page
- Define a New Object Type
- Define Realm Object Types with JavaScript Classes
- Supported Property Types
- Define Object Properties
- Specify an Optional Property
- Specify a Primary Key
- Index a Property
- Define a Default Property Value
- Remap a Property
- Define Relationship Properties
- Define a To-One Relationship Property
- Define a To-Many Relationship Property
- Define an Inverse Relationship Property
- Define an Embedded Object Property
Define a New Object Type
To define a Realm object type, create a schema object that specifies the type's
name
and properties
. The type name must be unique among object types in
a realm. For details on how to define specific properties, see Define
Object Properties.
const CarSchema = { name: "Car", properties: { make: "string", model: "string", miles: "int", } }
You can open a realm using the Realm Object you have defined.
// Open a local realm file with a particular path & predefined Car schema try { const realm = await Realm.open({ path: "myrealm", schema: [Car], }); } catch (err) { console.error("Failed to open the realm", err.message); }
Define Realm Object Types with JavaScript Classes
You can define Realm object types with JavaScript classes. To use a class as an
object type, define the object schema on the static property schema
.
class Car { static schema = { name: "Car", properties: { make: "string", model: "string", miles: "int", }, }; get carName() { return `${this.make} ${this.model}`; } }
Pass the class itself to the schema property of the Realm.Configuration object when opening a realm. You can then read and write normally.
const realm = await Realm.open({ path: "myrealm", schema: [Car], }); let car1; realm.write(() => { car1 = realm.create("Car", { make: "Nissan", model: "Sentra", miles: 1000, }); }); console.log(car1.carName); // use car1
Supported Property Types
Every property in a Realm object has a strongly defined data type. A property's type can be a primitive data type or an object type defined in the same realm. The type also specifies whether the property contains a single value or a list of values.
Realm Database supports the following primitive data types:
bool
for boolean valuesint
anddouble
, which map to JavaScriptnumber
valuesDecimal128
for high precision numbersstring
date
, which maps to Datedata
, which maps to ArrayBufferobjectId
, which maps to ObjectId
To specify that a field contains a list of a primitive value type, append []
to the type name.
Define Object Properties
To define a property for an object type, create a key-value pair representing
the name and data type of the property under the properties
field.
The following schema defines a Dog
type that has two properties: a string
name
and an integer age
.
const DogSchema = { name: "Dog", properties: { name: "string", age: "int" } };
Specify an Optional Property
To mark a property as optional, append a question mark ?
to its type.
The following schema defines a DogSchema with the optional property breed
of type string
.
const DogSchema = { name: "Dog", properties: { breed: "string?" } };
Specify a Primary Key
To specify a property as an object type's primary key, set the schema's
primaryKey
field to the property name.
A primary key is a property that uniquely identifies an object. Realm Database automatically indexes primary key properties, which allows you to efficiently read and modify objects based on their primary key.
If an object type has a primary key, then all objects of that type must include the primary key property with a value that is unique among objects of the same type in a realm. An object type may have at most one primary key. You cannot change the primary key property for an object type after any object of that type is added to a realm and you cannot modify an object's primary key value.
The following Task
object schema specifies the _id
property as its
primary key.
const TaskSchema = { name: 'Task', properties: { _id: 'objectId', _partition: 'string?', name: 'string', status: 'string', }, primaryKey: '_id', };
Index a Property
Realm supports indexing for string, integer, boolean, Date
, and ObjectId
properties. To define an index for a given property, set indexed
to
true
.
An index significantly increases the speed of certain read operations at the cost of slightly slower write times and additional storage overhead. Indexes are particularly useful for equality comparison, such as querying for an object based on the value of a property.
It's best to only add indexes when optimizing the read performance for specific situations.
The following Book
object schema defines an index on the name
property.
const BookSchema = { name: "Book", properties: { name: { type: "string", indexed: true }, price: "int", }, };
Define a Default Property Value
To define a default value, set the value of the property to an object with a
type
field and a default
field.
The following Car
object schema specifies a default value of 0
for
the miles
property:
const CarSchema = { name: "Car", properties: { make: "string", model: "string", miles: { type: "int", default: 0 }, }, };
Remap a Property
To use a different property name in your code than is stored in
Realm Database, set mapTo
to the name of the property as it appears in
your code.
A developer opens a realm using the following Dog
object schema.
Realm Database stores each dog's first name with the snake case
first_name
property. The schema maps the property to firstName
for
objects used in JavaScript code.
const DogSchema = { name: "Dog", properties: { _id: "string", first_name: { type: 'string', mapTo: 'firstName' } }, primaryKey: '_id' };
Define Relationship Properties
With Device Sync, you can also define your relationships in the App Services UI.
Define a To-One Relationship Property
A to-one relationship maps one property to a single instance of another object type. For example, you can model a person having at most one companion dog as a to-one relationship.
To define a to-one relationship property, specify the related object type name as the property type.
The following Person
object schema specifies that a person may or may not
own a single Dog
. If they do own a Dog
, Realm links to it via the
dog
property:
const Person = { name: "Person", properties: { name: "string", birthdate: "date", dog: "Dog?" } }; const Dog = { name: "Dog", properties: { name: "string", age: "int", breed: "string?" } };
Define a To-Many Relationship Property
A to-many relationship maps one property to zero or more instances of another object type. For example, you can model a person having any number of companion dogs as a to-many relationship.
To define a to-many relationship property, specify the related object type name as a list.
When you declare a to-one relationship in your object model, it must be an optional property. If you try to make a to-one relationship required, Realm throws an exception at runtime.
An application could use the following object schemas to indicate
that a Person may own multiple Dogs by including them in its dog
property:
const Person = { name: "Person", properties: { name: "string", birthdate: "date", dogs: "Dog[]" } }; const Dog = { name: "Dog", properties: { name: "string", age: "int", breed: "string?" } };
Define an Inverse Relationship Property
An inverse relationship property is an automatic backlink relationship. Realm Database automatically updates implicit relationships whenever an object is added or removed in a corresponding to-many list. You cannot manually set the value of an inverse relationship property.
To define an inverse relationship property, set the property type to
linkingObjects
and specify the object type and property name that define the
relationship to invert.
An application could use the following object schemas to indicate that a User may be assigned many Tasks and that each Task should automatically keep track of which User it's assigned to.
- The User object's
tasks
property is defined as a to-many relationship with Task objects and contains all of a given user's assigned tasks. - The Task object's
assignee
property inverts the relationship and automatically updates to refer back to any User object that contains the Task in itstasks
property.
Define an Embedded Object Property
To define a Realm object model with an embedded object (nested Realm
object), set embedded
to true
.
An embedded object exists as nested data inside of a single, specific parent object. It inherits the lifecycle of its parent object and cannot exist as an independent Realm object. Realm automatically deletes embedded objects if their parent object is deleted or when overwritten by a new embedded object instance.
You can reference an embedded object type from parent object types in the same way as a relationship.
An application requires two parent schemas, ContactSchema
and
BusinessSchema
. The application requires a child schema AddressSchema
that is embedded. A Business
object can embed a list of Address
objects, whereas a Contact
object can only embed a single Address
object.
const AddressSchema = { name: "Address", embedded: true, properties: { street: "string?", city: "string?", country: "string?", postalCode: "string?", }, }; const ContactSchema = { name: "Contact", primaryKey: "_id", properties: { _id: "objectId", name: "string", address: "Address", // Embed a single object }, }; const BusinessSchema = { name: "Business", primaryKey: "_id", properties: { _id: "objectId", name: "string", addresses: { type: "list", objectType: "Address" }, // Embed an array of objects }, };