Accessors — reading and writing model data
Cascade models hold their state in a single data object. You don’t manipulate it directly; you go through the accessor methods. This keeps dirty-tracking, dot-notation paths, and the change pipeline consistent — every read goes through one place, every write goes through another.
This guide is the field-level companion to CRUD basics. CRUD covers create/update/delete at the whole-model level; this page covers get, set, merge, assign, unset, increment, decrement, plus the typed shortcuts.
Reading — get(field, default?)
Section titled “Reading — get(field, default?)”const user = await User.find(123);
const name = user.get("name"); // anyconst email = user.get("email", "n/a"); // any, with defaultget reads a field from the model’s data. If the field is absent, it returns the default (or undefined if you didn’t pass one). This is the canonical reader for instance state.
Exact types from the schema
Section titled “Exact types from the schema”Type the model with the schema’s output type and get() / set() know every column:
import { Model, type ModelData } from "@warlock.js/cascade";import { v } from "@warlock.js/seal";
export const postSchema = v.object({ title: v.string().required(), views: v.int().default(0), publishedAt: v.date().nullable(), authorId: v.int().required().internal(),});
export type PostSchema = ModelData<typeof postSchema>;
export class Post extends Model<PostSchema> { public static table = "posts"; public static schema = postSchema;}
post.get("title"); // stringpost.get("views"); // number (a default makes it always present)post.get("publishedAt"); // Date | nullpost.get("publishedAt", new Date()); // Date (the default replaces null/undefined)post.get("tilte"); // type error: not a column of Post
post.set("views", 10); // okpost.set("views", "10"); // type error: string is not numberpost.set("publishedAt", null); // ok, the column is nullableModelData<typeof schema> is Infer.Output<typeof schema>: dates are Date, v.int() and v.number() are number, .nullable() adds | null, .optional() adds undefined, and .default() removes it. A model declared without a schema type (extends Model) keeps loose, any-typed access, so existing code keeps compiling.
Only top-level columns are typed. A dot path ("profile.address.city") is accepted for any column and returns any; pass a type argument when you want one: post.get<string>("meta.seoTitle"). The path is not checked on purpose, because a recursive path type is what makes large schemas slow to compile.
System columns
Section titled “System columns”Cascade’s own columns are part of the typed key space, so you do not declare them in the schema: get("id") is number, get("_id") is unknown (the MongoDB document id), get("created_at") and get("updated_at") are Date, and get("deleted_at") is Date | null. The camelCase spellings (createdAt, updatedAt, deletedAt) are accepted too, because MongoDB names them that way by default and Postgres uses snake case. Timestamp columns can be renamed or disabled per model, and the type cannot know which, so a model that renames or drops one declares that column in its schema. A column the schema declares always wins, so a model with string ids declares id: v.string().required() and get("id") is string. A Model<WithSystemColumns<Schema>> workaround keeps compiling.
Setting a column named at runtime
Section titled “Setting a column named at runtime”A wrong value reports on the value (Type 'string' is not assignable to type 'number'), not on the key. To set a column whose name is only known at runtime, type the key as a ModelKey and pass it to set(), which checks the value against that column:
import type { ModelKey, ModelValue } from "@warlock.js/cascade";
function setColumn<K extends ModelKey<PostSchema>>( post: Post, key: K, value: ModelValue<PostSchema, K>,) { post.set(key, value);}A plain string key is not accepted on a typed model. Narrow it first, or use merge({ [key]: value }), which is not checked per column.
A column is not a property
Section titled “A column is not a property”post.title is always undefined: the data lives in post.data, and the only property shortcuts are id, uuid, createdAt and updatedAt. Use post.get("title").
warlock checkreportspost.titlereads on Cascade models asWL9021andwarlock check --fixrewrites them topost.get("title").- In development (any
NODE_ENVexceptproduction) Cascade warns once per model and column the first time such a property is read. Nothing is installed in production.
Read-only snapshots
Section titled “Read-only snapshots”toDataSnapshot() returns a typed, read-only copy of the model’s data, without the hidden columns. Unlike toJSON() it ignores resource, resourceColumns and toJsonColumns, so its type is exactly the schema:
const snapshot = post.toDataSnapshot(); // ModelDataSnapshot<PostSchema>snapshot.publishedAt; // Date | nullUse ModelDataSnapshot<PostSchema> as the input type of a resource or presenter.
Dot-notation paths
Section titled “Dot-notation paths”JSON columns and nested objects walk by dot path:
const city = user.get("profile.address.city");const firstTag = post.get("tags.0");Same syntax as the query builder’s .where("profile.address.city", ...). No driver-specific differences.
Typed shortcuts
Section titled “Typed shortcuts”When you know the column’s type, the typed shortcuts return the value already narrowed (and default-typed):
const name = user.string("name"); // string | undefinedconst nameOrFallback = user.string("name", "Guest"); // string
const age = user.number("age"); // number | undefinedconst isActive = user.boolean("isActive", false); // booleanThe unprefixed names (string, number, boolean) keep call sites short. Useful when you want to skip the cast at every read site.
The id shortcut
Section titled “The id shortcut”The primary key shows up so often that Cascade exposes it as a direct property:
console.log(user.id); // number | string — same as user.get("id")No .get(...) needed for id. Every other column goes through get.
has(field) — is it present?
Section titled “has(field) — is it present?”if (user.has("profile.avatar")) { ... }Returns true if the field exists at the path, including when the value is null or an empty string. Distinguishes “the field is missing entirely” from “the field is set but falsy” — useful for soft-deleted, partially-loaded, or sparsely-populated documents.
isFilled(field) — does it hold a value?
Section titled “isFilled(field) — does it hold a value?”if (user.isFilled("profile.avatar")) { ... }Returns true when the field exists and is neither null nor undefined. An empty string, 0 and false count as filled.
The null contract: an unset column is null, not undefined
Section titled “The null contract: an unset column is null, not undefined”A column that was never set reads back as null from the SQL drivers (PostgreSQL): the column exists in the row, its value is SQL NULL. On MongoDB the same field is simply absent, so get() returns undefined. Cascade returns what the database stored and does not convert between the two.
The default in get(field, fallback) (and in string(), number(), boolean()) applies only when the field is missing, not when it holds null: user.get("nickname", "none") is null for an unset PostgreSQL column. Use user.get("nickname") ?? "none" for a fallback that covers both.
That makes value === undefined an unreliable “was this set” test: on PostgreSQL it is false for an unset column, so the code treats it as set. Use one of these instead:
user.isFilled("avatar"); // false for null and for missinguser.get("avatar") == null; // same test, inlineuser.has("avatar"); // NOT this: true for a null column on PostgreSQLNote that .optional() in a schema types the key as T | undefined, while a PostgreSQL row holds null for it. Check optional columns with isFilled() or == null, never with === undefined.
Writing — set(field, value)
Section titled “Writing — set(field, value)”user.set("name", "Ada Lovelace");user.set("profile.address.city", "NYC");await user.save();set updates one field. It also marks that field as dirty — Cascade knows you changed it and will send it on the next save(). Dot-paths work the same as get.
set returns the model, so you can chain or hand back the instance.
merge(values) — many fields at once
Section titled “merge(values) — many fields at once”user.merge({ name: "Ada", email: "ada@example.com", profile: { address: { city: "London" } },});await user.save();merge does a deep merge — nested objects are merged, not replaced. So merge({ profile: { address: { city: "London" } } }) keeps any other keys under profile.address (street, postcode) intact.
If you want a shallow replace instead, set the whole field with set:
user.set("profile", { address: { city: "London" } }); // wipes existing profileBoth record dirty state on the affected paths.
set(values) — set many fields at once
Section titled “set(values) — set many fields at once”Pass an object to set to write several fields in one call. Each entry behaves exactly like set(key, value) for that key, and every other field stays untouched. The rule is the same as for the single form: set replaces, merge deep-merges, and a dot path targets one leaf.
merge keeps nested keys the new value leaves out, so clearing a key of an object column with merge does nothing. A top-level key in set replaces the whole column, objects and arrays included:
// stored: { filters: { status: "open", owner: "ada" } }
user.merge({ filters: { status: "closed" } });// filters -> { status: "closed", owner: "ada" } owner is kept
user.set({ filters: { status: "closed" } });// filters -> { status: "closed" } owner is gone
user.set({ "filters.status": "closed" });// filters -> { status: "closed", owner: "ada" } only that leaf is writtenValues are cast, dirty-tracked and written as whole-field updates exactly as with the single form, and the method returns the model. In a typed model every key is a schema column, a system column or a dot path, and each value is checked against its column’s type.
set strips identity columns (id, _id, the primary key) from a persisted model just as merge does, so user.set(req.body) cannot retarget the save. Cascade has no guarded or fillable list: besides the identity columns, every key the schema accepts is written, nested objects included, and a key it doesn’t declare follows the model’s strictMode (stripped by default). Pick the fields you accept before passing a request body all the same.
A field path segment __proto__, constructor or prototype (set("__proto__.isAdmin", true), a request body key "__proto__.x"), or a __proto__ key anywhere inside a set() / merge() value, throws before anything is written: those names can never be columns, and following them would change every object in the process. unset() refuses the same path segments. A nested key that is merely named constructor ({ specs: { constructor: "Ford" } }) is ordinary data and stays allowed in merge().
Keys that overlap in one call, such as settings with settings.theme, or a.b with a.b.c, throw an error that names both keys before anything is written. Set the whole column or the leaf, not both.
unset(...fields) — remove a field
Section titled “unset(...fields) — remove a field”user.unset("nickname");user.unset("profile.avatar", "profile.coverImage");await user.save();Removes the field from the model’s data and records it as dirty. On save:
- MongoDB —
$unsetoperator removes the field from the document. - Postgres — the column is nullified (
UPDATE ... SET column = NULL).
The semantics differ at the storage layer (Mongo can have absent fields; SQL columns always exist with NULL), but at the model level it’s the same: user.get("nickname") will return undefined afterwards.
increment / decrement — atomic-style numeric updates
Section titled “increment / decrement — atomic-style numeric updates”user.increment("loginCount"); // +1user.increment("loginCount", 5); // +5user.decrement("creditsRemaining", 10);await user.save();These read the current value (defaulting to 0), add or subtract, and set the new value — all on the model instance. The dirty tracker picks up the change, and save() ships it.
:::caution — Instance-level, not race-safe
model.increment() is not the same as the query-builder .increment() you saw in the Querying essentials. The instance version reads-then-writes locally; if two processes both load the same row, increment, and save, you’ll have a lost-update race.
For race-safe atomic increments across processes, use the query-builder form:
await User.whereId(123).increment("loginCount");// → UPDATE ... SET loginCount = loginCount + 1 — single statement, no readRule of thumb: the instance form is fine when only this request is editing the row (validated user profile, single-writer flows). For counters, rate limits, or anything multi-writer, prefer the query-builder form.
:::
only(fields) — pluck a subset
Section titled “only(fields) — pluck a subset”const summary = user.only(["id", "name", "email"]);// → { id, name, email } — plain objectReturns a plain object containing just the listed fields. Useful for building API responses, fixtures, or comparison snapshots without going through full serialization. Doesn’t mark anything dirty — it’s a read.
Default values
Section titled “Default values”When you read a field that isn’t set, three sources can populate the default:
- The explicit second argument to
get/string/number/boolean:user.get("status", "active"). - The schema’s
.default(...)validator on the field:v.enum([...]).default("active"). This applies during write —create()andsave()fill in defaults before persisting — so on subsequent reads the field is set, no default needed. undefined— Cascade doesn’t invent values out of nowhere.
The general rule: defaults belong in the schema (consistent across every call site), not scattered through get calls.
What about setData(data) / mergeData(data) for whole-model replacements?
Section titled “What about setData(data) / mergeData(data) for whole-model replacements?”If you have a fresh data object from somewhere and want to swap or merge it into the model wholesale:
user.merge(freshData); // deep-merge into model.dataFor a complete overwrite you’d usually create a new model instance rather than mutate an existing one — that’s clearer than reaching for low-level state replacement.
Going further
Section titled “Going further”- Dirty tracking — what
set/merge/unsetrecord, and how to inspect it: Dirty tracking guide - Bulk-row atomic increments (race-safe) — Querying essentials + Query Builder API reference
- JSON path operations — JSON fields guide
- Schema defaults and validation — validation guide