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

Group aliases accept a union-shaped context that mirrors every operation in the group. Only the fields relevant to the current operation are populated. Returning a context from the hook replaces the operation args, just like per-operation hooks.

// Soft-delete pattern: filter out deleted docs on every write operation.
.("modify", () => ({
  ...,
  : { ...., : { : false } },
}));

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