Schema Builder
Build schemas with `M` and infer types from the same definition
The schema builder is the heart of Mongster. It gives you a typed way to describe collection shapes, validation rules, defaults, indexes, and timestamps.
import { , } from "mongster";
const = ({
: .().(1),
: .().(),
: .().(0).(),
}).();
type = M.<typeof >;
type = M.<typeof >;Top-level exports
M: the builder namespace.defineSchema(shape): equivalent toM.schema(shape).M.infer<typeof schema>: stored document type.M.inferInput<typeof schema>: create and insert input type.
Builder methods
| Category | Methods |
|---|---|
| Primitives | string, number, boolean, date |
| BSON | objectId, decimal, binary |
| Composites | object, array, tuple, fixedArrayOf, union, oneOf, schema |
M.tuple vs M.fixedArrayOf
Both produce the same fixed-length tuple schema. tuple(items) takes a single array; fixedArrayOf(...items) takes items as positional arguments.
const = .([.(), .()]);
const = .(.(), .());The two are functionally identical. Prefer M.tuple([...]) for consistency with the rest of the API.
M.union vs M.oneOf
Both produce the same union schema. union(...shapes) takes items as arguments; oneOf([...shapes]) takes a single array.
const = .(.(), .());
const = .([.(), .(), .()]);Common field chainers
These are available on every primitive and composite schema.
- Validation:
min,max,enum,match,validate. - Shape modifiers:
optional,nullable. - Defaults:
default,defaultFn. - Index metadata:
index,uniqueIndex,sparseIndex,partialIndex,hashedIndex,textIndex,ttl,expires.
validate(fn, message?)
Attach a custom validator that runs after the built-in checks. Return true to accept, false to reject with the optional message.
const = .()
.(/^[A-Z]{2}$/)
.(
() => ["CA", "NY", "TX", "WA"].(),
"State code must be one of: CA, NY, TX, WA",
);bsonSubType(value) (Binary)
Set the BSON sub-type on a Binary schema. The full list of accepted values:
type BinarySubtype =
| Binary.SUBTYPE_DEFAULT // 0
| Binary.SUBTYPE_FUNCTION // 1
| Binary.SUBTYPE_BYTE_ARRAY // 2
| Binary.SUBTYPE_UUID // 4
| Binary.SUBTYPE_MD5 // 5
| Binary.SUBTYPE_ENCRYPTED // 6
| Binary.SUBTYPE_COLUMN // 7
| Binary.SUBTYPE_SENSITIVE // 8
| Binary.SUBTYPE_VECTOR // 9
| Binary.SUBTYPE_USER_DEFINED; // 128Validation rejects incoming Binary values whose sub_type does not match.
const = .().(.);
const = .().(.);Schema-level helpers
These are methods on the schema instance returned by M.schema(...).
withTimestamps(config?)— adds managedcreatedAt/updatedAt.addIndex(keys, options?)— declares compound indexes.pre(op, fn)andpost(op, fn)— schema-level hooks.
See the Schema Reference for the full method list, including getShape, clone, getHooks, and collectIndexes.
withTimestamps configuration
const = .({ : .() }).({
: "madeAt",
: false,
});config accepts:
createdAt?: boolean | string— set tofalseto drop, or a string to rename.updatedAt?: boolean | string— same.
When enabled, Mongster auto-injects $currentDate: { updatedAt: true } on every update operation, and $currentDate: { createdAt: true } on upserts that insert a new document.
Type inference
Two type helpers pull a document and an input shape from a schema. Use them wherever you would have written a TypeScript interface by hand.
type User = M.<typeof >;type CreateUser = M.<typeof >;M.infer<typeof schema>produces the stored document shape._id, timestamps, and any auto-managed fields are added.M.inferInput<typeof schema>produces the create / update input shape._idand timestamps become optional, defaults become optional, and.optional()/.nullable()fields become optional with their declared inner type.