Mongster

Guides

Schema

Schema is the main building block of Mongster models

A Mongster schema describes one collection shape. Define it once, then reuse it for runtime validation, inferred types, and index metadata.

Start with M.schema()

import {  } from "mongster";

const  = .({
  : .().(1).(200),
  : .().(false),
  : .().([1, 2, 3]).(2),
  : .(.()).([]),
  : .().(),
  : .().(),
})
  .({ : 1, : 1 })
  .();

type  = M.<typeof >;
type  = M.<typeof >;

What the schema gives you

  • runtime validation for creates and updates,
  • a stored document type via M.infer,
  • an input type via M.inferInput,
  • field-level and collection-level index definitions,
  • optional timestamps through withTimestamps().

Nested shapes stay explicit

import {  } from "mongster";

const  = .({
  : .({
    : .().(1),
    : .().("UTC"),
  }),
  : .(
    .({
      : .(),
      : .(),
    }),
  ).([]),
});

Practical advice

  • Use M.object() for embedded documents instead of ad-hoc nested values.
  • Put compound indexes on the schema with addIndex().
  • Use withTimestamps() for collections that naturally track lifecycle dates.
  • Declare refs directly in the schema with M.objectId().ref(() => Model) when another collection is involved.

On this page