Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
데이터 유형

내장된 객체 - React Native SDK

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

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

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

  • 연락처의 이름과 주소 세부 정보를 나타내는 React 상태 변수를 생성합니다.

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

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

  • submitContact()를 호출하는 "연락처 제출" 버튼에 onPress 이벤트 추가합니다.

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

점 표기법을 사용하여 내장된 객체 속성 값을 기준으로 객체 컬렉션을 필터링하거나 정렬할 수 있습니다.

다음 ContactList 예시에서는 포함된 Address 객체를 필터링하고 쿼리합니다.

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

  • Contact 클래스를 useQuery 후크에 전달하여 연락처에 대한 쿼리를 전달합니다.

  • 쿼리 "name == 'John Smith'"collection.filtered() 를 전달하여 이름이 'John Smith'인 연락처를 필터링합니다.

  • 점 표기법을 사용하여 연락처의 도로명 주소를 조회합니다.

1const ContactList = ({postalCode}) => {
2 // Run the `.filtered()` method on all the returned Contacts to get
3 // contacts with a specific postal code.
4 const contactsInArea = useQuery(
5 Contact,
6 contacts => {
7 return contacts.filtered(`address.postalCode == '${postalCode}'`);
8 },
9 [postalCode],
10 );
11
12 if (contactsInArea.length) {
13 return (
14 <>
15 <FlatList
16 testID='contactsList'
17 data={contactsInArea}
18 renderItem={({item}) => {
19 <Text>{item.name}</Text>;
20 }}
21 />
22 </>
23 );
24 } else {
25 return <Text>No contacts found in this area.</Text>;
26 }
27};
1const ContactList = ({postalCode}: {postalCode: string}) => {
2 // Run the `.filtered()` method on all Contact objects to get
3 // contacts with a specific postal code.
4 const contactsInArea = useQuery(Contact, contacts => {
5 return contacts.filtered(`address.postalCode == '${postalCode}'`);
6 });
7
8 if (contactsInArea.length) {
9 return (
10 <>
11 <FlatList
12 data={contactsInArea}
13 renderItem={({item}) => {
14 <Text>{item.name}</Text>;
15 }}
16 />
17 </>
18 );
19 } else {
20 return <Text>No contacts found in this area.</Text>;
21 }
22};

내장된 객체의 속성을 업데이트하려면 쓰기 트랜잭션(write transaction)에서 속성을 수정합니다.

다음 UpdateContact 예에서는 포함된 Address 객체의 street 속성을 업데이트합니다.

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

  • 연락처의 새 주소를 나타내는 React 상태 변수를 생성합니다.

  • Contact 클래스를 useQuery 후크에 전달하고 구성 요소에 전달된 이름과 일치하는 연락처를 프롭으로 필터링하여 모든 연락처에 대한 쿼리를 수행합니다. .

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

  • 쓰기 트랜잭션(write transaction)을 수행하고 연락처의 상세 주소를 street 상태 변수 값으로 설정하는 컴포넌트 메서드 updateStreet()을(를) 만듭니다.

  • street 상태 변수를 표시하고 변경하는 TextInput을(를) 렌더링합니다.

  • 호출하는 'Update Street Address' 버튼에 onPress 이벤트 추가합니다.updateStreet()

1// Find the contact you want to update
2const UpdateContact = ({contactId}) => {
3 const [street, setStreet] = useState('');
4 const contact = useObject(Contact, contactId);
5 const realm = useRealm();
6
7 const updateStreet = () => {
8 // Modify the property of the embedded Address object in a write transaction
9 realm.write(() => {
10 // Update the address directly through the contact
11 contact.address.street = street;
12 });
13 };
14
15 return (
16 <View>
17 <Text>{contact.name}</Text>
18 <TextInput
19 value={street}
20 onChangeText={setStreet}
21 placeholder='Enter New Street Address'
22 />
23 <Button
24 onPress={updateStreet}
25 title='Update Street Address'
26 />
27 </View>
28 );
29};
1// Find the contact you want to update
2const UpdateContact = ({contactId}: {contactId: Realm.BSON.ObjectId}) => {
3 const [street, setStreet] = useState('');
4 const contact = useObject(Contact, contactId);
5 const realm = useRealm();
6
7 const updateStreet = () => {
8 // Modify the property of the embedded Address object in a write transaction
9 realm.write(() => {
10 // Update the address directly through the contact
11 contact!.address.street = street;
12 });
13 };
14
15 return (
16 <View>
17 <Text>{contact!.name}</Text>
18 <TextInput
19 value={street}
20 onChangeText={setStreet}
21 placeholder='Enter New Street Address'
22 />
23 <Button
24 onPress={updateStreet}
25 title='Update Street Address'
26 />
27 </View>
28 );
29};

내장된 객체를 덮어쓰려면 쓰기 트랜잭션(write transaction)에서 당사자의 내장된 객체 속성을 새 인스턴스에 다시 할당합니다.

다음 OverwriteContact 예시에서는 포함된 Address 객체를 덮어씁니다.

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

  • 연락처의 새 주소를 나타내는 React 상태 변수를 만듭니다.

  • Contact 클래스를 useQuery 후크에 전달하고 구성 요소에 전달된 이름과 일치하는 연락처를 프롭으로 필터링하여 모든 연락처에 대한 쿼리를 수행합니다. .

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

  • 쓰기 트랜잭션(write transaction)을 수행하는 구성요소 메소드 updateAddress()을(를) 생성하고 Contact 객체의 기존 주소를 덮어쓰는 새 Address 객체를 생성합니다.

  • 새 주소의 상태 변수를 표시하고 변경하는 TextInput 구성요소를 렌더링합니다.

  • 호출하는 'Overwrite Address' 버튼에 onPress 이벤트 추가합니다.updateAddress()

1const OverwriteContact = ({contactId}) => {
2 const [street, setStreet] = useState('');
3 const [city, setCity] = useState('');
4 const [country, setCountry] = useState('');
5 const [postalCode, setPostalCode] = useState('');
6 const contact = useObject(Contact, contactId);
7 const realm = useRealm();
8
9 const updateAddress = () => {
10 realm.write(() => {
11 // Within a write transaction, overwrite the embedded object with the new address
12 const address = {
13 street,
14 city,
15 country,
16 postalCode,
17 };
18
19 contact.address = address;
20 });
21 };
22 return (
23 <View>
24 <Text>{contact.name}</Text>
25 <Text>Enter the new address:</Text>
26 <TextInput
27 value={street}
28 onChangeText={setStreet}
29 placeholder='Street'
30 />
31 <TextInput value={city} onChangeText={setCity} placeholder='City' />
32 <TextInput
33 value={country}
34 onChangeText={setCountry}
35 placeholder='Country'
36 />
37 <TextInput
38 value={postalCode}
39 onChangeText={setPostalCode}
40 placeholder='Postal Code'
41 />
42 <Button
43 onPress={updateAddress}
44 title='Overwrite Address'
45 />
46 </View>
47 );
48};
1const OverwriteContact = ({
2 contactId,
3}: {
4 contactId: Realm.BSON.ObjectId;
5}) => {
6 const [street, setStreet] = useState('');
7 const [city, setCity] = useState('');
8 const [country, setCountry] = useState('');
9 const [postalCode, setPostalCode] = useState('');
10 const contact = useObject(Contact, contactId);
11 const realm = useRealm();
12
13 const updateAddress = () => {
14 realm.write(() => {
15 // Within a write transaction, overwrite the embedded object with the new address
16 const address = {
17 street,
18 city,
19 country,
20 postalCode,
21 };
22
23 contact!.address = address;
24 });
25 };
26
27 return (
28 <View>
29 <Text>{contact!.name}</Text>
30 <Text>Enter the new address:</Text>
31 <TextInput
32 value={street}
33 onChangeText={setStreet}
34 placeholder='Street'
35 />
36 <TextInput value={city} onChangeText={setCity} placeholder='City' />
37 <TextInput
38 value={country}
39 onChangeText={setCountry}
40 placeholder='Country'
41 />
42 <TextInput
43 value={postalCode}
44 onChangeText={setPostalCode}
45 placeholder='Postal Code'
46 />
47 <Button
48 onPress={updateAddress}
49 title='Overwrite Address'
50 />
51 </View>
52 );
53};

Realm은 내장된 객체에 계단식 삭제를 사용합니다. 내장된 객체를 삭제하려면 내장된 객체의 상위 항목을 삭제합니다.

다음 DeleteContact 예시에서는 내장된 객체와 해당 상위 객체를 삭제합니다.

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

  • Contact 클래스를 useQuery 후크에 전달하여 연락처에 대한 쿼리를 전달합니다.

  • 구성 요소에 prop으로 전달된 이름과 일치하는 Contact 객체를 필터링합니다.

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

  • 쓰기 트랜잭션(write transaction)을 수행하는 구성 요소 메서드 deleteContact() 을(를) 생성하고 Realm.delete() 를 호출하여 Contact 객체를 제거합니다.

  • deleteContact()를 호출하는 "연락처 삭제" 버튼에 onPress 이벤트 추가합니다.

1const ContactInfo = ({contactCity, postalCode}) => {
2 const realm = useRealm();
3 const parentsToDelete = useQuery(
4 Contact,
5 contacts => {
6 return contacts.filtered(`address.city == '${contactCity}'`);
7 },
8 [contactCity],
9 );
10 const embeddedToDelete = useQuery(
11 Contact,
12 contacts => {
13 return contacts.filtered(`address.postalCode == '${postalCode}'`);
14 },
15 [postalCode],
16 );
17
18 const deleteParentObject = () => {
19 realm.write(() => {
20 // Delete all objects that match the filter.
21 // Also deletes embedded objects.
22 realm.delete(parentsToDelete);
23 });
24 };
25
26 const deleteEmbeddedObject = () => {
27 realm.write(() => {
28 embeddedToDelete.forEach(contact => {
29 // Delete just the embedded object.
30 realm.delete(contact.address);
31 });
32 });
33 };
34
35 return (
36 <View>
37 <Text testID='contactCityText'>{contactCity}</Text>
38 <Button
39 onPress={deleteParentObject}
40 title='Delete Contact'
41 />
42 <Button
43 onPress={deleteEmbeddedObject}
44 title='Delete Address'
45 />
46 </View>
47 );
48};
1type ContactInfoProps = {
2 contactCity: string;
3 postalCode: string;
4};
5
6const ContactInfo = ({contactCity, postalCode}: ContactInfoProps) => {
7 const parentsToDelete = useQuery(Contact, contacts => {
8 return contacts.filtered(`address.city == '${contactCity}'`);
9 });
10 const embeddedToDelete = useQuery(Contact, contacts => {
11 return contacts.filtered(`address.postalCode == '${postalCode}'`);
12 });
13 const realm = useRealm();
14
15 const deleteParentObject = () => {
16 realm.write(() => {
17 // Delete all objects that match the filter.
18 // Also deletes embedded objects.
19 realm.delete(parentsToDelete);
20 });
21 };
22
23 const deleteEmbeddedObject = () => {
24 realm.write(() => {
25 embeddedToDelete.forEach(contact => {
26 // Delete just the embedded object.
27 realm.delete(contact.address);
28 });
29 });
30 };
31
32 return (
33 <View>
34 <Text testID='contactCityText'>{contactCity}</Text>
35 <Button
36 onPress={deleteParentObject}
37 title='Delete Contact'
38 />
39 <Button
40 onPress={deleteEmbeddedObject}
41 title='Delete Address'
42 />
43 </View>
44 );
45};

돌아가기

UUID

이 페이지의 내용