Skip to main content

๐Ÿง‘โ€๐Ÿ’ป Models: Your Data, Supercharged!

Models are the heart of Cascade! They turn raw MongoDB documents into powerful, object-oriented toolsโ€”making your code cleaner, safer, and way more fun. ๐ŸŽ‰

๐Ÿค” What is a Model?โ€‹

A model is a class that represents a single document in a collection. It gives you methods and properties to create, update, delete, and fetch documents, all with a sprinkle of magic.

๐Ÿšซ Why Not Just Use Documents Directly?โ€‹

Because as your app grows, you'll want:

  • Auto-generated IDs (no more manual work!)
  • Type casting and validation
  • Embedded documents
  • Events and hooks
  • Syncing related data (see below!)
  • Recycle bin and soft deletes
  • ...and so much more!

โœจ Creating a Modelโ€‹

Just extend the Model class and set the collection property:

src/models/user.ts
import { Model } from "@warlock.js/cascade";

export class User extends Model {
/**
* The collection name (required)
*/
public static collection = "users";
}

๐Ÿ—๏ธ Instantiating a Modelโ€‹

You can create a model instance with initial data:

src/app.ts
import { User } from "./models/user";

const user = new User({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

This just creates the instanceโ€”the data isn't saved yet!

๐Ÿ’พ Saving a Modelโ€‹

Call save() to persist your model:

src/app.ts
import { User } from "./models/user";

async function main() {
const user = new User({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

await user.save();
}

Or use the static create method for a one-liner:

src/app.ts
const user = await User.create({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

๐Ÿ†” Accessing Document IDsโ€‹

MongoDB gives you a unique _id (ObjectId), but Cascade also gives you a friendly numeric id:

console.log(user._id); // ObjectId("5f9b2b3b3f3b9a0b3c3b9a0b")
console.log(user.id); // 1424151
Did you know?

Cascade can auto-generate sequential or random IDs for youโ€”no more manual ID headaches!

๐Ÿช„ Why Models Rock in Cascadeโ€‹

  • Auto-casting: Your data is always the right type.
  • Embedded docs: Nest models inside models, easily.
  • Events: Run code before/after create, update, delete, and more.
  • Syncing: Keep related data up-to-date automatically (unique to Cascade!).
  • Recycle bin: Soft delete with easy restore.
  • Default values: Set defaults for any field.
  • Custom casting: Generate slugs, computed fields, and more.

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