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 >;

withTimestamps configuration

withTimestamps() accepts an object that lets you rename or disable the managed fields.

const  = .({ : .() }).({
  : "madeAt",
  : false,
});

config.createdAt and config.updatedAt accept:

  • true (the default) — keep the field with the name createdAt / updatedAt.
  • false — drop the field from the inferred type and skip writing it.
  • "customName" — rename the field.

When timestamps are enabled, Mongster automatically appends $currentDate: { updatedAt: true } to every update operation, and adds $currentDate: { createdAt: true } on upserts that actually insert a new document. See Updates for the operator details.

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(). See Indexes for the full helper set.
  • 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