Para agregar un nuevo objeto Realm a una instancia de reino, utilice realm.create() dentro de una transacción de escritura. Si el esquema incluye el tipo de objeto y este se ajusta a él, Realm lo almacena.
El ejemplo para crear un objeto utiliza el siguiente esquema:
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?', }, }; }
Para crear un nuevo objeto:
Acceda a una instancia de reino usando el
useRealm()gancho.Crea
handleAddPerson(), que crea un nuevo objetoPersonbasado en el valor de TextInput.Agregar un onPressevento en el botón de envío que llama
handleAddPerson()a.
1 const 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 };
Create an Object with a To-One Relationship
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:
Query the realm for a pre-existing Pet object. Assign the result to
newPet.Create a new PetOwner object and pass
newPetto thepetproperty.Envuelve tu transacción de escritura en una función
handleAddPetOwner(), que crea un nuevo objetoPetOwnercon unPetasociado.Add an onPress event on the submit button that calls
handleAddPetOwner().
1 const 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 };
Create an Object with a To-Many Relationship
En una relación uno a muchos, un objeto puede estar relacionado con varios objetos de un tipo específico. Para obtener más información sobre las relaciones uno a muchos, consulte Relaciones y objetos incrustados.
El ejemplo para crear un objeto con una relación de uno a muchos utiliza el siguiente esquema para indicar que una empresa puede emplear a varios Empleados:
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:
Query the realm for all pre-existing Employee objects using useQuery().
Create a new Company object and pass the results of your previous query to the
employeesproperty.Wrap your write transaction in a
handleAddCompany()function, which creates a newCompanyobject with an associated list ofEmployees.Add an onPress event on the submit button that calls
handleAddCompany().
1 const 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 };
Cree un Objeto incrustado
Un objeto incrustado es un objeto que existe como datos anidados dentro de un objeto padre; no puede existir como un objeto Realm independiente. Para aprender más sobre objetos incrustados, consulta Relaciones y objetos incrustados.
The example for representing an embedded object uses the following schema that allows you to embed a single Address into a new Contact object:
1 class 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 }
1 class 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 }
1 class 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 }
1 class 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 }
1 class 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 }
1 class 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 }
Para crear un objeto incrustado, asigna una instancia del objeto incrustado a una propiedad del objeto principal.
El siguiente ejemplo de CreateContact crea un nuevo objeto Contact con un objeto Address incrustado.
The CreateContact component does the following:
Creates React state variables that represent the contact's name and address details.
Gets access to an open realm instance by calling the
useRealm()hook within the component.Creates a component method
submitContact()that performs a write transaction to create a newAddressembedded object andContactparent object based on theTextInputvalues for the contact's name and address.Adds an onPress event on the "Submit Contact" button that calls
submitContact().
1 const 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 };
Create an Asymmetric Object
Un objeto asimétrico permite sincronizar una colección unidireccionalmente desde el dispositivo a la base de datos Atlas si se utiliza la sincronización flexible. Para obtener más información sobre los objetos asimétricos, consulte "Transmitir datos a 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', }, }; }
Puedes crear un objeto asimétrico dentro de una transacción de escritura usando realm.create(). Al crear un objeto asimétrico, Realm.create() devuelve undefined en lugar del objeto mismo.
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()} /> ); };