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
/ /
CRUD

CRUD - borrar - SDK de React Native

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

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:

  1. Consigue acceso a la instancia Realm abierto llamando al hook useRealm().

  2. Retrieve all dogs in the realm instance by passing Dog to the useQuery() hook.

  3. Crea un método de componente deleteDog() que reciba como parámetro un objeto Dog. Dentro del método, pasamos Realm.delete() el objeto Dog, borrándolo del realm.

  4. Mapa través de los perros para representar una lista de Text componentes que contienen un de name perro y un botón "Eliminar perro".

  5. 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.

You can delete multiple objects from a realm in a couple of ways:

  1. 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.

  2. 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:

  1. Retrieve the realm instance using the useRealm() hook.

  2. Set a variable myDogs to all the Dog objects by passing the Dog class to the useQuery() hook.

  3. Create a component method deleteAllYoungDogObjects() that performs a write transaction. Within the write transaction, we set a variable, youngDogs, to the result of myDogs.filtered() with a query to obtain all dogs younger than three. Then pass youngDogs to realm.delete(), deleting all young dogs from the realm.

  4. Crea un método de componente deleteAllDogObjects() que realiza una transacción de escritura. Dentro de la transacción de escritura, pasamos myDogs a realm.delete(), eliminando todos los perros del dominio.

  5. Mapa a través de los perros para renderizar una lista de Text componentes que contienen name y age de un perro.

  6. Add an onPress event on the "Delete Young Dog Objects" button that calls deleteAllYoungDogObjects(), deleting all young dogs from the realm, which triggers a re-render and removes them from the UI.

  7. Agrega un evento onPress en el botón "borrar todos los objetos Dog" que llama a deleteAllDogObjects(), 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'
/>
</>
);
};

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:

  1. Obtenga acceso a la instancia del reino abierto llamando al gancho useRealm() dentro del componente.

  2. Cree un método de componente deleteAllData() que realice una transacción de escritura y llame a Realm.deleteAll(), borrando todos los objetos del realm.

  3. Agregue un evento onPress al botón "Eliminar todos los datos" que llame a deleteAllData().

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.

Volver

Update

En esta página