Skip to main content

๐Ÿ—‘๏ธ Destroying Models

Sometimes, you need to say goodbye to your data. Cascade makes deleting (and restoring!) models safe, easy, and powerful. ๐Ÿ’ฅ

๐Ÿงน Deleting a Modelโ€‹

Just call destroy() on a model instance:

src/app.ts
const category = await Category.find(1);
if (category) {
await category.destroy();
}

Or use the static destroy method:

src/app.ts
await Category.destroy(1); // By ID
await Category.destroy({ name: "Sports" }); // By filter

๐Ÿฆบ Soft Deletes (The Safety Net!)โ€‹

By default, Cascade uses soft deletesโ€”your data isn't really gone, just marked as deleted! (Unless you say otherwise.)

src/models/category.ts
export class Category extends Model {
public static collection = "categories";
public softDelete = true; // This is the default!
}

When you destroy a model, it sets the deletedAt field instead of removing the document. You can still query, restore, or force-delete it later!

โ™ป๏ธ Restoring Soft-Deleted Modelsโ€‹

Bring your data back from the grave:

src/app.ts
const category = await Category.find(1, { withTrashed: true });
if (category && category.isTrashed()) {
await category.restore();
}

Or restore many at once:

src/app.ts
await Category.restore({ isActive: false });

๐Ÿ’ฃ Force Delete (No Going Back!)โ€‹

Want to really, truly, permanently delete? Use forceDelete:

src/app.ts
await category.forceDelete(); // Instance method
await Category.forceDelete(1); // Static method
danger

Force delete is permanent! Use with care. (There's no undo.)

โšก Model Events: Deletion Hooksโ€‹

Cascade's event system lets you hook into deletion actions:

src/app/main.ts
Category.events()
.onDeleting((category) => console.log("Deleting!"))
.onDeleted((category) => console.log("Deleted!"));

Use these for logging, cleanup, or syncing related data.

๐Ÿง™โ€โ™‚๏ธ Pro Tipโ€‹

Soft deletes are great for audit trails and accidental-deletion recovery. But if you need to save space or comply with regulations, use force delete!


๐ŸŒŸ What's Next?โ€‹