Mongster

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 to M.schema(shape).
  • M.infer<typeof schema>: stored document type.
  • M.inferInput<typeof schema>: create and insert input type.

Builder methods

CategoryMethods
Primitivesstring, number, boolean, date
BSONobjectId, decimal, binary
Compositesobject, 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;   // 128

Validation 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 managed createdAt / updatedAt.
  • addIndex(keys, options?) — declares compound indexes.
  • pre(op, fn) and post(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 to false to 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 User = {
    _id: ObjectId;
    name: string;
    email: string;
    createdAt: Date;
    updatedAt: Date;
}
type CreateUser = M.<typeof >;
type CreateUser = {
    name: string;
    email: string;
    createdAt?: Date | undefined;
    updatedAt?: Date | undefined;
    _id?: ObjectId | undefined;
}
  • 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. _id and timestamps become optional, defaults become optional, and .optional() / .nullable() fields become optional with their declared inner type.

On this page