Docs 菜单
Docs 主页
/ /
Atlas Device SDKs
/ /

CRUD — 更新 — React Native SDK

在此页面上

  • 创建具有对一关系的对象
  • 创建具有对多关系的对象
  • 创建嵌入式对象
  • 创建非对称对象

要将新的Realm 对象添加到域实例,请使用 域() 在一个写事务(write transaction)中。 如果模式包含对象类型并且对象符合模式,则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. 创建 handleAddPerson(),根据 TextInput 值创建新的 Person 对象。

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

在一对一关系中,一个对象最多与特定类型的另一个对象相关。要了解有关一对一关系的更多信息,请参阅关系和嵌入式对象

创建具有一对一关系的对象的示例使用以下模式,来表示“宠物主人”只能拥有一只“宠物”:

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

创建与另一个对象具有对一关系的对象:

  1. 在 Realm 中查询预先存在的 Pet 对象。将结果赋给 newPet

  2. 创建一个新的 PetOwner 对象,并将 newPet 传递给 pet 属性。

  3. 将写事务封装在 handleAddPetOwner() 函数中,该函数会创建一个具有关联的 Pet 的新 PetOwner 对象。

  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. 将写事务封装在 handleAddCompany() 函数中,该函数会创建一个具有 Employees 关联列表的新 Company 对象。

  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 对象存在。如需了解有关嵌入对象的更多信息,请参阅“关系和嵌入对象”。

表示嵌入式对象的示例使用以下模式,可允许您将单个 Address 嵌入到新的 Contact 对象中:

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. 创建执行写事务的组件方法 submitContact(),以根据联系人姓名和地址的 TextInput 值创建新的 Address 嵌入式对象和 Contact 父对象。

  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 数据库:

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

您可以使用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