Batch Deleting Entities
Deleting multiple records efficiently is critical when managing large datasets. Onyx Database provides batch operations to delete entities in bulk. This tutorial demonstrates how to perform batch deletions using Onyx's ORM.
Steps to Batch Delete Entities (Onyx Cloud Database)
1
Persist Test Data
Create a collection of entities to be deleted later. These entities will be persisted in the database.
1const people = [];
2for (let i = 0; i < 1000; i++) {
3 people.push({
4 firstName: `TestName_${i}`,
5 lastName: `TestLastName_${i}`,
6 dateCreated: new Date(),
7 });
8}
9await db.save("Person", people);
- Ensure all required fields for each entity are populated.
2
Query the Persisted Entities
Retrieve the recently persisted entities to confirm they are stored in the database.
1const savedPeople = await db.from("Person").list();
2console.log(`${savedPeople.length} people saved`);
- Verify the number of retrieved entities matches the number saved.
3
Batch Delete the Entities
Use the
delete
method to remove the collection of entities from the database in a single operation.1await db.delete("Person", savedPeople);
- All entities in the collection must be of the same type.
- Avoid deleting too many entities at once to prevent memory issues.
4
Verify the Deletion
Query the database again to confirm the entities were successfully deleted.
1const remainingPeople = await db.from("Person").list();
2console.log(`${remainingPeople.length} people remain after deletion`);
- The query should return no results if the deletion was successful.
Important Notes
- Batch operations improve performance by reducing the number of database calls.
- Be cautious of memory usage when handling large batches of entities.
Troubleshooting
- Entities Not Deleted: Ensure the entities being passed to the
delete
method are the same ones retrieved from the database. - Memory Issues: Break large collections into smaller batches and delete them sequentially.
Next Steps
Once you have mastered deleting entities, explore related topics: