Mongster

Guides

Hooks

You control how your data is processed on each query

Hooks exist at two levels:

  • schema hooks, attached to the schema definition,
  • model hooks, attached to a specific model instance.
import { ,  } from "mongster";

const  = .({
  : .(),
  : .(),
});

.("createOne", () => {
  return {
    : {
      ....,
      : ...(),
    },
  };
});

.("find", () => {
  .(..);
});

const  = ("users", );

.("modify", () => {
  return {
    ...,
    : {
      ....,
      : { : false },
    },
  };
});

Supported group aliases

  • save: insertOne, insertMany, createOne, createMany
  • modify: updateOne, updateMany, findOneAndUpdate, replaceOne, findOneAndReplace, upsertOne
  • remove: deleteOne, deleteMany, findOneAndDelete

Execution order

When both schema and model hooks are present, the order is:

  1. model pre hook
  2. schema pre hook
  3. database operation
  4. schema post hook
  5. model post hook

Practical advice

  • Use schema hooks for rules that belong to the data shape itself.
  • Use model hooks for collection-specific behavior.
  • Keep hook logic small and predictable, especially for write paths.

On this page