Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

CRUD - Create - React Native SDK

On this page

  • Create an Object with a To-One Relationship
  • Create an Object with a To-Many Relationship
  • Create an Embedded Object
  • Create an Asymmetric Object

To add a new Realm object to a realm instance, use realm.create() inside of a write transaction. If the schema includes the object type and the object conforms to the schema, then Realm stores the object.

The example for creating an object uses the following schema:

class Person extends Realm.Object {
static schema = {
name: 'Person',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
age: 'int?',
},
};
}
class Person extends Realm.Object<Person> {
_id!: Realm.BSON.ObjectId;
name!: string;
age?: number;
static schema: ObjectSchema = {
name: 'Person',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
age: 'int?',
},
};
}

To create a new object:

  1. Access a realm instance using the useRealm() hook.

  2. Create handleAddPerson(), which creates a new Person object based on the TextInput value.

  3. Add an onPress event on the submit button that calls handleAddPerson().

1const CreatePersonInput = () => {
2 const [name, setName] = useState('');
3 const realm = useRealm();
4
5 const handleAddPerson = () => {
6 realm.write(() => {
7 realm.create('Person', {_id: PERSON_ID, name: name, age: 25});
8 });
9 };
10
11 return (
12 <>
13 <TextInput value={name} onChangeText={setName} />
14 <Button
15 onPress={() => handleAddPerson()}
16 title='Add Person'
17 />
18 </>
19 );
20};

In a one-to-one relationship, an object is related to at most one other object of a particular type. To learn more about one-to-one relationships, refer to to Relationships & Embedded Objects.

The example for creating an object with a to-one relationship uses the following schema to indicate that a Pet Owner may only own one Pet:

class Pet extends Realm.Object {
static schema = {
name: 'Pet',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
age: 'int',
animalType: 'string?',
},
};
}
class PetOwner extends Realm.Object {
static schema = {
name: 'PetOwner',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
age: 'int',
pet: 'Pet?',
},
};
}
class Pet extends Realm.Object<Pet> {
_id!: Realm.BSON.ObjectId;
name!: string;
age!: number;
animalType!: string;
static schema: ObjectSchema = {
name: 'Pet',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
age: 'int',
animalType: 'string?',
},
};
}
class PetOwner extends Realm.Object<PetOwner> {
_id!: Realm.BSON.ObjectId;
name!: string;
age?: number;
pet?: Pet;
static schema: ObjectSchema = {
name: 'PetOwner',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
age: 'int',
pet: 'Pet?',
},
};
}

To create an object with a to-one relationship to another object:

  1. Query the realm for a pre-existing Pet object. Assign the result to newPet.

  2. Create a new PetOwner object and pass newPet to the pet property.

  3. Wrap your write transaction in a handleAddPetOwner() function, which creates a new PetOwner object with an associated Pet.

  4. Add an onPress event on the submit button that calls handleAddPetOwner().

1const CreatePetOwnerInput = () => {
2 const [ownerName, setOwnerName] = useState('');
3 const realm = useRealm();
4 const newPet = useObject(Pet, PET_ID);
5
6 const handleAddPetOwner = () => {
7 // Create a new Pet Owner object, pass new Pet object in pet field
8 realm.write(() => {
9 realm.create('PetOwner', {
10 _id: PETOWNER_ID,
11 name: ownerName,
12 age: 25,
13 pet: newPet,
14 });
15 });
16 };
17
18 return (
19 <>
20 <TextInput
21 onChangeText={setOwnerName}
22 value={ownerName}
23
24 />
25 <Button
26 onPress={() => handleAddPetOwner()}
27 title='Add New Pet Owner'
28 />
29 </>
30 );
31};

In a one-to-many relationship, an object may be related to multiple objects of a particular type. To learn more about one-to-many relationships, refer to to Relationships & Embedded Objects.

The example for creating an object with a to-many relationship uses the following schema to indicate that a Company may employ multiple Employees:

class Employee extends Realm.Object {
static schema = {
name: 'Employee',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
birthdate: 'date',
},
};
}
class Company extends Realm.Object {
static schema = {
name: 'Company',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
employees: {
type: 'list',
objectType: 'Employee',
optional: false,
},
},
};
}
class Employee extends Realm.Object<Employee> {
_id!: Realm.BSON.ObjectId;
name!: string;
birthdate!: Date;
static schema: ObjectSchema = {
name: 'Employee',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
birthdate: 'date',
},
};
}
class Company extends Realm.Object<Company> {
_id!: Realm.BSON.ObjectId;
name!: string;
employees!: Realm.List<Employee>;
static schema: ObjectSchema = {
name: 'Company',
primaryKey: '_id',
properties: {
_id: 'objectId',
name: 'string',
employees: {
type: 'list',
objectType: 'Employee',
optional: false,
},
},
};
}

To create an object with a to-many relationship to another object:

  1. Query the realm for all pre-existing Employee objects using useQuery().

  2. Create a new Company object and pass the results of your previous query to the employees property.

  3. Wrap your write transaction in a handleAddCompany() function, which creates a new Company object with an associated list of Employees.

  4. Add an onPress event on the submit button that calls handleAddCompany().

1const CreateNewCompanyInput = () => {
2 const employees = useQuery(Employee);
3 const [companyName, setCompanyName] = useState('');
4 const realm = useRealm();
5
6 // Create a new Company and connect our list of Employees to it
7 const handleCreateCompany = () => {
8 realm.write(() => {
9 realm.create('Company', {
10 _id: COMPANY_ID,
11 name: companyName,
12 employees: employees,
13 });
14 });
15 };
16
17 return (
18 <>
19 <TextInput
20 onChangeText={setCompanyName}
21 value={companyName}
22
23 />
24 <Button
25 onPress={() => handleCreateCompany()}
26 title='Add New Company'
27 />
28 </>
29 );
30};

An embedded object is an object that exists as data nested inside of a parent object; it cannot exist as an independent Realm object. To learn more about embedded objects, refer to to Relationships & Embedded Objects.

The example for representing an embedded object uses the following schema that allows you to embed a single Address into a new Contact object:

1class Address extends Realm.Object {
2 static schema = {
3 name: 'Address',
4 embedded: true, // default: false
5 properties: {
6 street: 'string?',
7 city: 'string?',
8 country: 'string?',
9 postalCode: 'string?',
10 },
11 };
12}
1class Contact extends Realm.Object {
2 static schema = {
3 name: 'Contact',
4 primaryKey: '_id',
5 properties: {
6 _id: 'objectId',
7 name: 'string',
8 // Embed a single object
9 address: 'Address',
10 },
11 };
12}
1class Business extends Realm.Object {
2 static schema = {
3 name: 'Business',
4 primaryKey: '_id',
5 properties: {
6 _id: 'objectId',
7 name: 'string',
8 // Embed an array of objects
9 addresses: {type: 'list', objectType: 'Address'},
10 },
11 };
12}
1class Address extends Realm.Object<Address> {
2 street?: string;
3 city?: string;
4 country?: string;
5 postalCode?: string;
6
7 static schema: ObjectSchema = {
8 name: 'Address',
9 embedded: true, // default: false
10 properties: {
11 street: 'string?',
12 city: 'string?',
13 country: 'string?',
14 postalCode: 'string?',
15 },
16 };
17}
1class Contact extends Realm.Object {
2 _id!: string;
3 name!: string;
4 address!: Address;
5
6 static schema: ObjectSchema = {
7 name: 'Contact',
8 primaryKey: '_id',
9 properties: {
10 _id: 'objectId',
11 name: 'string',
12 // Embed a single object
13 address: 'Address',
14 },
15 };
16}
1class Business extends Realm.Object {
2 _id!: string;
3 name!: string;
4 addresses!: Realm.List<Address>;
5
6 static schema: ObjectSchema = {
7 name: 'Business',
8 primaryKey: '_id',
9 properties: {
10 _id: 'objectId',
11 name: 'string',
12 // Embed an array of objects
13 addresses: {type: 'list', objectType: 'Address'},
14 },
15 };
16}

To create an embedded object, assign an instance of the embedded object to a parent object's property.

The following CreateContact example creates a new Contact object with an embedded Address object.

The CreateContact component does the following:

  1. Creates React state variables that represent the contact's name and address details.

  2. Gets access to an open realm instance by calling the useRealm() hook within the component.

  3. Creates a component method submitContact() that performs a write transaction to create a new Address embedded object and Contact parent object based on the TextInput values for the contact's name and address.

  4. Adds an onPress event on the "Submit Contact" button that calls submitContact().

1const CreateContact = () => {
2 const [name, setContactName] = useState('');
3 const [street, setStreet] = useState('');
4 const [city, setCity] = useState('');
5 const [country, setCountry] = useState('');
6 const [postalCode, setPostalCode] = useState('');
7 const realm = useRealm();
8
9 const submitContact = () => {
10 // Create a Contact within a write transaction
11 realm.write(() => {
12 // Create an embedded Address object
13 const address = {
14 street,
15 city,
16 country,
17 postalCode,
18 };
19
20 realm.create('Contact', {
21 _id: new Realm.BSON.ObjectID(),
22 name,
23 // Embed the address in the Contact object
24 address,
25 });
26 });
27 };
28 return (
29 <View>
30 <TextInput value={name} onChangeText={text => setContactName(text)} />
31 <TextInput value={street} onChangeText={text => setStreet(text)} />
32 <TextInput value={city} onChangeText={text => setCity(text)} />
33 <TextInput value={country} onChangeText={text => setCountry(text)} />
34 <TextInput
35 value={postalCode}
36 onChangeText={text => setPostalCode(text)}
37 />
38 <Button
39 title='Submit Contact'
40 onPress={submitContact}
41 />
42 </View>
43 );
44};

An asymmetric object allows you to sync a collection unidirectionally from your device to your Atlas database, if you are using Flexible Sync. To learn more about asymmetric objects, refer to to Stream Data to Atlas.

The example for creating an asymmetric object uses the following schema that defines a Weather Sensor object for sending weather-related data one-way from your device to your Atlas database:

class WeatherSensor extends Realm.Object {
static schema = {
name: 'WeatherSensor',
// sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: '_id',
properties: {
_id: 'objectId',
deviceId: 'string',
temperatureInFahrenheit: 'int',
barometricPressureInHg: 'float',
windSpeedInMph: 'float',
},
};
}
class WeatherSensor extends Realm.Object<WeatherSensor> {
_id!: Realm.BSON.ObjectId;
deviceId!: string;
temperatureInFahrenheit!: number;
barometricPressureInHg!: number;
windSpeedInMph!: number;
static schema: ObjectSchema = {
name: 'WeatherSensor',
// sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: '_id',
properties: {
_id: 'objectId',
deviceId: 'string',
temperatureInFahrenheit: 'int',
barometricPressureInHg: 'float',
windSpeedInMph: 'float',
},
};
}

You can create an asymmetric object inside a write transaction using realm.create(). When creating an asymmetric object, Realm.create() returns undefined rather than the object itself.

const App = () => {
// Getting access to our opened realm instance
const realm = useRealm();
const handleAddSensor = () => {
realm.write(() => {
realm.create('WeatherSensor', {
_id: weatherSensorPrimaryKey,
deviceId: 'WX1278UIT',
temperatureInFahrenheit: 66.7,
barometricPressureInHg: 29.65,
windSpeedInMph: 2,
});
});
};
return (
<Button
title='Add A New Sensor'
onPress={() => handleAddSensor()}
/>
);
};

Back

CRUD