문서 메뉴
문서 홈
/ /
Atlas Device SDK
/ /

CRUD - 생성 - React Native SDK

이 페이지의 내용

  • To-One 관계가 있는 객체 만들기
  • 대다(To-Many) 관계로 객체 만들기
  • 임베디드 객체 생성
  • 비대칭 객체 생성

Realm 인스턴스에 새 Realm 객체를 추가하려면 쓰기 트랜잭션(write transaction) 내에서 realm.create() 를 사용합니다. 스키마 에 객체 유형이 포함되어 있고 객체가 스키마를 준수하는 경우 Realm은 객체를 저장합니다.

객체를 만드는 예제에서는 다음 스키마를 사용합니다:

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

새 객체를 만들려면:

  1. useRealm() 훅을 사용하여 Realm 인스턴스에 액세스합니다.

  2. TextInput 값을 기반으로 새 Person 객체를 만드는 handleAddPerson()을 만듭니다.

  3. onPress 추가 를 호출하는 제출 버튼의 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};

일대일(one-to-one) 관계는 객체가 특정 유형의 다른 객체 최대 하나와 관련되어 있음을 의미합니다. 일대일 관계에 대해 자세히 알아보려면 관계 & 포함된 객체 를 참조하세요.

대일 관계가 있는 객체를 만드는 예제에서는 다음 스키마를 사용하여 애완동물 소유자가 애완동물을 한 마리만 소유할 수 있음을 나타냅니다.

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-one 관계를 갖는 객체를 생성하려면 다음을 수행합니다:

  1. Realm에서 기존 Pet 객체를 쿼리합니다. 결과를 newPet에 할당합니다.

  2. 새 PetOwner 객체를 만들고 newPetpet 속성에 전달합니다.

  3. 연관된 Pet 와 함께 새 PetOwner 객체를 생성하는 handleAddPetOwner() 함수로 쓰기 트랜잭션을 래핑합니다.

  4. onPress 추가 를 호출하는 제출 버튼의 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};

일대다 관계에서 객체는 특정 유형의 여러 객체와 관련될 수 있습니다. 일대다 관계에 대해 자세히 알아보려면 관계 & 포함된 객체를 참조하세요.

대다 관계가 있는 객체를 생성하는 예에서는 다음 스키마를 사용하여 회사가 여러 직원을 고용할 수 있음을 나타냅니다.

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

다른 객체와 대다 관계가 있는 객체를 만들려면 다음과 같이 하세요:

  1. useQuery()를 사용하여 기존의 모든 임직원 객체에 대한 Realm을 쿼리합니다.

  2. 새 Company 객체를 만들고 이전 쿼리 결과를 employees 속성에 전달합니다.

  3. Employees 관련 목록이 있는 새 Company 객체를 생성하는 handleAddCompany() 함수로 쓰기 트랜잭션을 래핑합니다.

  4. onPress 추가 를 호출하는 제출 버튼의 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};

포함된 객체는 부모 객체 내부에 중첩된 데이터로 존재하는 객체이며 독립적인 Realm 객체로는 존재할 수 없습니다. 포함된 객체에 대해 자세히 알아보려면 관계 & 임베디드 객체를 참조하세요.

포함된 객체를 나타내는 예제에서는 단일 주소를 새 문의 객체에 포함할 수 있는 다음 스키마를 사용합니다.

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}

포함된 객체를 생성하려면 포함된 객체의 인스턴스를 상위 객체의 속성에 할당합니다.

다음 CreateContact 예제에서는 Address 객체가 포함된 새 Contact 객체를 만듭니다.

CreateContact 컴포넌트는 다음을 수행합니다.

  1. 연락처의 이름과 주소 세부 정보를 나타내는 React 상태 변수를 만듭니다.

  2. 컴포넌트 내에서 useRealm() 훅을 호출하여 열린 Realm 인스턴스에 대한 액세스 권한을 얻습니다.

  3. 연락처 이름 및 주소의 TextInput 값을 기반으로 쓰기 트랜잭션을 수행하여 새 Address 포함된 객체와 Contact 상위 객체를 생성하는 컴포넌트 메서드 submitContact() 를 생성합니다.

  4. onPress 추가 를 호출하는 "연락처 제출" 버튼의 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};

비대칭 객체를 사용하면 Flexible Sync를 사용하는 경우 기기에서 Atlas 데이터베이스로 컬렉션을 단방향으로 동기화할 수 있습니다. 비대칭 객체에 대해 자세히 알아보려면 Atlas로 데이터 스트리밍을 참조하세요.

비대칭 객체를 만드는 예제에서는 기기의 날씨 관련 데이터를 Atlas 데이터베이스로 일방향으로 전송하기 위한 Weather Sensor 객체를 정의하는 다음 스키마를 사용합니다.

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

쓰기 트랜잭션(write transaction) 내에서 realm.create() 를 사용하여 비대칭 객체를 만들 수 있습니다. 비대칭 객체를 만들 때 Realm.create() 는 객체 자체가 아닌 undefined 를 반환합니다.

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

돌아가기

CRUD

다음

읽기