Skip to content

Defining models

Models in JSORM are pure metadata. They contain field definitions, relations, and database configuration, but no logic or queries.

import { defineModel, t, r } from "@jsorm/core";
export const User = defineModel("users", {
db: "main",
fields: {
id: t.uuid().primary().autoCreate(),
name: t.string(100),
email: t.string(255).unique(),
password: t.string().hidden(),
roleId: t.uuid().nullable(),
active: t.boolean().default(true),
createdAt: t.dateTime().autoCreate(),
updatedAt: t.dateTime().autoUpdate(),
},
relations: {
posts: r.hasMany("post"),
role: r.belongsTo("role", { localKey: "roleId" }),
},
});

Use t.* to define field types. Each type returns a FieldChain with chainable modifiers.

t.string(length?) // FieldChain<"string">
t.uuid() // FieldChain<"uuid">
t.boolean() // FieldChain<"boolean">
t.integer() // FieldChain<"integer">
t.decimal(precision?, scale?) // FieldChain<"decimal">
t.text() // FieldChain<"text">
t.dateTime() // FieldChain<"dateTime">
t.json() // FieldChain<"json">
t.enum(values) // FieldChain<"enum">
Modifier Description
.primary() Marks as primary key
.autoCreate() Auto-generated on creation
.autoUpdate() Updated on each modification
.default(value) Default value
.unique() Unique constraint
.nullable() Allows null
.hidden() Excluded from SELECT by default
// Primary key
id: t.uuid().primary().autoCreate(),
// Strings
name: t.string(100).unique(),
email: t.string(255).unique(),
password: t.string(255).hidden(),
// Boolean
active: t.boolean().default(true),
// Numbers
age: t.integer(),
price: t.decimal(10, 2),
// Text (long content)
bio: t.text().nullable(),
// Date/time
createdAt: t.dateTime().autoCreate(),
updatedAt: t.dateTime().autoUpdate(),
// JSON (flexible structure)
metadata: t.json().nullable(),
// Enum
status: t.enum(["active", "inactive", "archived"]),

Use r.* to define relations:

relations: {
role: r.belongsTo("role", { localKey: "roleId" }),
posts: r.hasMany("post"),
profile: r.hasOne("profile"),
roles: r.manyToMany("role", {
through: "user_roles",
localForeignKey: "userId",
foreignForeignKey: "roleId",
}),
}

See Relations for more details.