Guides
Data Types
Primitives, BSON helpers, and composite shapes
Mongster gives you a small set of schema builders that map well to MongoDB data while keeping the resulting TypeScript types precise.
import { , } from "mongodb";
import { } from "mongster";
const = .({
: .().(1).(120),
: .().(0),
: .().(false),
: .().(),
: .(),
: .().(16),
: .().(.("0.00")),
: .(.()).([]),
: .([.(), .()]),
: .({
: .(),
: .().(),
}),
: .(.().(["draft", "live"]), .().([0, 1])),
});
type = M.<typeof >;
type = M.<typeof >;
const = new (.("1234567890abcdef"));Core builders
| Builder | Use for | Common methods |
|---|---|---|
M.string() | text values | min, max, enum, match, default, defaultFn |
M.number() | numeric values | min, max, enum, default, defaultFn |
M.boolean() | booleans | default, defaultFn |
M.date() | dates and timestamps | min, max, ttl, expires, default, defaultFn |
M.objectId() | MongoDB object ids | default, defaultFn, ref |
M.decimal() | Decimal128 values | default, defaultFn |
M.binary() | Binary / buffer data | min, max, bsonSubType, default, defaultFn |
Composite builders
M.object(shape)for embedded documents.M.array(schema)for lists.M.tuple([...])orM.fixedArrayOf(...)for fixed-position arrays.M.union(...)orM.oneOf([...])when a field can take multiple shapes.
Modifiers and validation
- Use
optional()when a field may be omitted entirely. - Use
nullable()whennullis a valid stored value. - Use
validate()when you need a custom runtime rule.
import { } from "mongster";
const = .().(() => .("-"), "Slug must contain a dash");Refs are explicit
Use M.objectId().ref(() => Model) when a field points at another Mongster model. At the moment, .ref() is terminal, so do not chain optional(), nullable(), or defaults after it.