Skip to content

Lifecycle & transactions

Hooks

Register pre / post hooks for create | update | delete. A pre hook can mutate the payload or throw to abort the operation; hooks may be async.

ts
User.pre("create", (doc) => { doc.email = doc.email.toLowerCase(); });
User.post("create", (user) => audit("user.created", user._id));

User.pre("update", (patch) => { /* patch is the $set payload */ });
User.pre("delete", (ids) => audit("user.deleting", ids)); // matched _ids
User.post("delete", (result) => audit("user.deleted", result.deleted));

Hooks are registered on the model and run for every operation of that kind, whether invoked via the manager or a chained QuerySet.

Transactions

Run several writes atomically with dorm.transaction. It commits on success and aborts on error. Pass the session to each write via .session(session) or create(data, { session }).

ts
await dorm.transaction(async (session) => {
  const user = await User.objects.create({ email }, { session });
  await Account.objects.filter({ owner: user._id }).session(session).update({ active: true });
});

WARNING

Transactions require a replica-set (or mongos) deployment — MongoDB doesn't support them on a standalone server. For local testing, a single-node replica set works (e.g. mongodb-memory-server's MongoMemoryReplSet).

Errors

  • DormValidationError — thrown by create / update on invalid input. It collects all failing fields in .errors ({ field, code, message, … }[]); .toJsonResponse() returns { message, errors }. The top-level .field / .code mirror the first error.

    ts
    try {
      await User.objects.create(req.body);
    } catch (err) {
      if (err instanceof DormValidationError) {
        return res.status(400).json(err.toJsonResponse());
      }
      throw err;
    }
    CodeMeaning
    DORM_ERROR_1required field missing
    DORM_ERROR_2type mismatch
    DORM_ERROR_3custom validate hook threw
    DORM_ERROR_4not unique (app-level check on unique fields, on create & update)
  • DoesNotExist / MultipleObjectsReturned — thrown by get() when a query matches zero or more than one document.

Released under the MIT License.