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

Common field chainers

  • Validation: min, max, enum, match, validate
  • Shape modifiers: optional, nullable
  • Defaults: default, defaultFn
  • Index metadata: index, uniqueIndex, sparseIndex, partialIndex, hashedIndex, textIndex, ttl, expires

Schema-level helpers

  • withTimestamps()
  • addIndex()
  • pre() and post()

On this page