Skip to main content

๐Ÿงฉ Embedded Documents

MongoDB lets you nest documents inside each otherโ€”Cascade makes this powerful and easy! Use embedded documents to keep related data together, reduce joins, and make your data model shine. ๐ŸŒŸ

๐Ÿค What Are Embedded Documents?โ€‹

An embedded document is just a document inside another document. For example, a Post can embed a Category.

๐Ÿ—๏ธ How to Embed a Documentโ€‹

  1. Define your models:
  2. Just use the model class in your casts!
src/models/post.ts
import { Model, Casts } from "@warlock.js/cascade";
import { Category } from "./category";

export class Post extends Model {
public static collection = "posts";
protected casts: Casts = {
title: "string",
content: "string",
category: Category, // Just pass the model class!
};
}
Did you know?

You no longer need to use castModel(Category)โ€”just pass the model class directly! This is the new, recommended way. castModel is still supported for backward compatibility.

Now, when you create a post and pass a category id, Cascade will fetch and embed the category data for you!

๐ŸŽฏ Controlling Embedded Dataโ€‹

By default, all fields are embedded. But you can control what gets embedded:

1. embeddedData Getterโ€‹

Override this getter in your model to specify exactly what to embed:

src/models/category.ts
public get embeddedData() {
return this.only(["id", "name"]);
}

2. embedded Propertyโ€‹

Or, just list the fields you want:

src/models/category.ts
public embedded = ["id", "name"];

3. embedAllExceptTimestampsAndUserColumnsโ€‹

Exclude timestamps and user columns from embedding:

src/models/category.ts
public embedAllExceptTimestampsAndUserColumns = true;

4. embedAllExceptโ€‹

Exclude specific fields:

src/models/category.ts
public embedAllExcept = ["createdAt", "updatedAt"];

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

You can combine these options for fine-grained control over what gets embedded!

info

Embedded documents are perfect for denormalizing data and making reads super fast. But be mindful of document size limits in MongoDB!


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