The examples on this page use the following schema:
class Dog extends Realm.Object { static schema = { name: 'Dog', properties: { name: 'string', owners: { type: 'list', objectType: 'Person', optional: true, }, age: 'int?', }, }; }
class Dog extends Realm.Object<Dog> { name!: string; owner?: Realm.List<Person>; age?: number; static schema: ObjectSchema = { name: 'Dog', properties: { name: 'string', owners: { type: 'list', objectType: 'Person', optional: true, }, age: 'int?', }, }; }
Eliminar un objeto
Para eliminar un objeto de un reino, pase el objeto a Realm.delete() dentro de una transacción de escritura.
En el siguiente ejemplo de un DogList componente, nosotros:
Consigue acceso a la instancia Realm abierto llamando al hook
useRealm().Retrieve all dogs in the realm instance by passing
Dogto theuseQuery()hook.Crea un método de componente
deleteDog()que reciba como parámetro un objetoDog. Dentro del método, pasamosRealm.delete()el objetoDog, borrándolo del realm.Agregue un evento onPress en el botón "Borrar perro" que llama al método
deleteDog()del componente.
const DogList = () => { const realm = useRealm(); const myDogs = useQuery(Dog); const deleteDog = deletableDog => { realm.write(() => { realm.delete(deletableDog); }); }; return ( <> {myDogs.map(dog => { return ( <> <Text>{dog.name}</Text> <Button onPress={() => deleteDog(dog)} title='Delete Dog' /> </> ); })} </> ); };
const DogList = () => { const realm = useRealm(); const myDogs = useQuery(Dog); const deleteDog = (deletableDog: Dog) => { realm.write(() => { realm.delete(deletableDog); }); }; return ( <> {myDogs.map(dog => { return ( <> <Text>{dog.name}</Text> <Button onPress={() => deleteDog(dog)} title='Delete Dog' /> </> ); })} </> ); };
Importante
No utilices objetos después de borrar
You cannot access or modify an object after you have deleted it from a Realm. If you try to use a deleted object, Realm throws an error.
Delete Multiple Objects
You can delete multiple objects from a realm in a couple of ways:
To delete all objects of a given object type from a realm, pass the results of useQuery(<ObjectType>) to the Realm.delete() method inside of a write transaction.
Para eliminar muchos objetos específicos de un realm, pasa Collection.filtered() a
Realm.delete()dentro de una transacción de escritura.
In the following example of a DogList component, we:
Retrieve the realm instance using the
useRealm()hook.Set a variable
myDogsto all theDogobjects by passing theDogclass to theuseQuery()hook.Create a component method
deleteAllYoungDogObjects()that performs a write transaction. Within the write transaction, we set a variable,youngDogs, to the result ofmyDogs.filtered()with a query to obtain all dogs younger than three. Then passyoungDogstorealm.delete(), deleting all young dogs from the realm.Crea un método de componente
deleteAllDogObjects()que realiza una transacción de escritura. Dentro de la transacción de escritura, pasamosmyDogsarealm.delete(), eliminando todos los perros del dominio.Mapa a través de los perros para renderizar una lista de
Textcomponentes que contienennameyagede un perro.Add an
onPressevent on the "Delete Young Dog Objects" button that callsdeleteAllYoungDogObjects(), deleting all young dogs from the realm, which triggers a re-render and removes them from the UI.Agrega un evento
onPressen el botón "borrar todos los objetos Dog" que llama adeleteAllDogObjects(), borrando todos los Dog del realm, lo que activa una re-renderización y los remueve de la Interfaz de Usuario.
Nota
When you delete objects from the realm instance, the component automatically re-renders and removes them from the UI.
const DogList = () => { const realm = useRealm(); const myDogs = useQuery(Dog); const deleteAllYoungDogObjects = () => { const youngDogs = useQuery(Dog, dogs => { return dogs.filtered('age < 3'); }); realm.write(() => { realm.delete(youngDogs); }); }; const deleteAllDogObjects = () => { realm.write(() => { realm.delete(myDogs); }); }; return ( <> {myDogs.map(dog => { return ( <> <Text>{dog.name}</Text> <Text>{dog.age}</Text> </> ); })} <Button onPress={() => deleteAllYoungDogObjects()} title='Delete Young Dog Objects' /> <Button onPress={() => deleteAllDogObjects()} title='Delete All Dog Objects' /> </> ); };
const DogList = () => { const realm = useRealm(); const myDogs = useQuery(Dog); const deleteAllYoungDogObjects = () => { const youngDogs = useQuery(Dog, dogs => { return dogs.filtered('age < 3'); }); realm.write(() => { realm.delete(youngDogs); }); }; const deleteAllDogObjects = () => { realm.write(() => { realm.delete(myDogs); }); }; return ( <> {myDogs.map(dog => { return ( <> <Text>{dog.name}</Text> <Text>{dog.age}</Text> </> ); })} <Button onPress={() => deleteAllYoungDogObjects()} title='Delete Young Dog Objects' /> <Button onPress={() => deleteAllDogObjects()} title='Delete All Dog Objects' /> </> ); };
Delete All Objects in a Realm
Para eliminar todos los objetos del realm, llama al Realm.deleteAll() dentro de una transacción de escritura. Esto borra el realm de todas las instancias de objetos, pero no afecta el esquema del realm.
In the following example of a DeleteProfileSettingsScreen component, we:
Obtenga acceso a la instancia del reino abierto llamando al gancho
useRealm()dentro del componente.Cree un método de componente
deleteAllData()que realice una transacción de escritura y llame aRealm.deleteAll(), borrando todos los objetos del realm.Agregue un evento
onPressal botón "Eliminar todos los datos" que llame adeleteAllData().
const DeleteProfileSettingsScreen = () => { const realm = useRealm(); const deleteAllData = () => { realm.write(() => { realm.deleteAll(); }); }; return ( <> <Text>Delete all data in your profile:</Text> <Button onPress={deleteAllData} title='Delete all data' /> </> ); };
const DeleteProfileSettingsScreen = () => { const realm = useRealm(); const deleteAllData = () => { realm.write(() => { realm.deleteAll(); }); }; return ( <> <Text>Delete all data in your profile:</Text> <Button onPress={deleteAllData} title='Delete all data' /> </> ); };
Tip
Borrar todos en desarrollo
Realm.deleteAll() es un método útil para limpiar rápidamente tu realm durante el desarrollo. Por ejemplo, en lugar de escribir una migración para actualizar objetos a un nuevo esquema, puede ser más rápido eliminar y luego regenerar los objetos con la propia aplicación.