Navigation

Define a Realm Object Schema - Node.js SDK

On this page

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 Car = {
name: "Car",
properties: {
make: "string",
model: "string",
miles: "int",
}
}
Note

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);
}

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 data 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

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 values
  • int and double, which map to JavaScript number values
  • Decimal128 for high precision numbers
  • string
  • date, which maps to Date
  • data, which maps to ArrayBuffer
  • objectId, which maps to ObjectId

To specify that a field contains a list of a primitive value type, append [] to the type name.

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.

Example

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"
}
};

To mark a property as optional, append a question mark ? to its type.

Example

The following schema defines a DogSchema with the optional property breed of type string.

const DogSchema = {
name: "Dog",
properties: {
breed: "string?"
}
};

To specify a property as an object type's primary key, set the schema's primaryKey field to the property name.

Note

A primary key is a string or integer 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.

Example

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',
};

Realm supports indexing for string, integer, boolean, Date, and ObjectId properties. To define an index for a given property, set indexed to true.

Note

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.

Example

The following Book object schema defines an index on the name property.

const BookSchema = {
name: "Book",
properties: {
name: { type: "string", indexed: true },
price: "int",
},
};

To define a default value, set the value of the property to an object with a type field and a default field.

Example

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 },
},
};

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.

Example

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'
};

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.

Example

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?"
}
};

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.

Example

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?"
}
};

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.

Example

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 its tasks property.

To define a Realm object model with an embedded object (nested Realm object), set embedded to true.

Note

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.

Example

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
},
};
Give Feedback

On this page