Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
データ型

UUID - React Native SDK

バージョン realm@10.5.0の新機能

UUID (汎用一意識別子)は バイトの16 の一意の値 です。UUID はBSON (Realm.BSON.UUID )の一部としてRealmパッケージにバンドルされています。

オブジェクトの一意の識別子としてUUIDを使用できます。 UUIDインデックス作成可能 であり、プライマリキーとして使用できます。

class Profile extends Realm.Object {
static schema = {
name: 'Profile',
primaryKey: '_id',
properties: {
_id: 'uuid',
name: 'string',
},
};
}
class Profile extends Realm.Object<Profile> {
_id!: Realm.BSON.UUID;
name!: string;
static schema: ObjectSchema = {
name: 'Profile',
primaryKey: '_id',
properties: {
_id: 'uuid',
name: 'string',
},
};
}

プロパティをUUIDとして定義するには、オブジェクトモデルでそのタイプを"uuid"に設定します。 書込みトランザクション (write transaction) 内に Realm オブジェクトを作成します。 オブジェクトの一意の識別子プロパティをランダム値に設定するには、 new UUID()を呼び出します。 または、 new UUID()に string を渡して、一意の識別子プロパティを特定の値に設定します。

次のCreateProfileInputの例では、 _idフィールドにuuid型を持つProfile Realm.Objectを作成します。

CreateProfileInputコンポーネントは次の処理を実行します。

  • useRealm()フックを呼び出して、開かれた Realm インスタンスへのアクセスを取得します。

  • 名前状態変数を作成します
    プロファイルの名前を表す "name" と呼ばれる。
  • 書込みトランザクションを実行するcreateProfileメソッドを作成します。 Within
    その書込みトランザクションでは、「name」状態変数のname値と新しいUUIDオブジェクトの_id値を持つProfileオブジェクトが作成されます。
  • ユーザーが次の名前を入力できるようにするTextInputコンポーネントをレンダリングします。
    プロファイルを参照してください。 ユーザーが [Create Profile(プロファイルの作成)] ボタンを押すと、 createProfileメソッドが呼び出され、 Profileオブジェクトが作成されます。
1const CreateProfileInput = () => {
2 const realm = useRealm();
3 const [name, setName] = useState('');
4
5 // createProfile creates a new 'Profile' Realm Object with a new UUID based on user input
6 const createProfile = () => {
7 realm.write(() => {
8 realm.create('Profile', {
9 name,
10 _id: new Realm.BSON.UUID(),
11 });
12 });
13 };
14 return (
15 <View>
16 <TextInput
17 placeholder='Name'
18 onChangeText={setName}
19 />
20 <Button
21 title='Create Profile'
22 onPress={createProfile}
23 />
24 </View>
25 );
1const CreateProfileInput = () => {
2 const realm = useRealm();
3 const [name, setName] = useState('');
4
5 // createProfile creates a new 'Profile' Realm Object with a new UUID based on user input
6 const createProfile = () => {
7 realm.write(() => {
8 realm.create('Profile', {
9 name,
10 _id: new Realm.BSON.UUID(),
11 });
12 });
13 };
14 return (
15 <View>
16 <TextInput
17 placeholder='Name'
18 onChangeText={setName}
19 />
20 <Button
21 title='Create Profile'
22 onPress={createProfile}
23 />
24 </View>
25 );

戻る

混合

項目一覧