Mongster

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

BuilderUse forCommon methods
M.string()text valuesmin, max, enum, match, default, defaultFn
M.number()numeric valuesmin, max, enum, default, defaultFn
M.boolean()booleansdefault, defaultFn
M.date()dates and timestampsmin, max, ttl, expires, default, defaultFn
M.objectId()MongoDB object idsdefault, defaultFn, ref
M.decimal()Decimal128 valuesdefault, defaultFn
M.binary()Binary / buffer datamin, max, bsonSubType, default, defaultFn

Composite builders

  • M.object(shape) for embedded documents.
  • M.array(schema) for lists.
  • M.tuple([...]) or M.fixedArrayOf(...) for fixed-position arrays.
  • M.union(...) or M.oneOf([...]) when a field can take multiple shapes.

Modifiers and validation

  • Use optional() when a field may be omitted entirely.
  • Use nullable() when null is 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.

On this page