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.
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 }).
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 bycreate/updateon invalid input. It collects all failing fields in.errors({ field, code, message, … }[]);.toJsonResponse()returns{ message, errors }. The top-level.field/.codemirror the first error.tstry { await User.objects.create(req.body); } catch (err) { if (err instanceof DormValidationError) { return res.status(400).json(err.toJsonResponse()); } throw err; }Code Meaning DORM_ERROR_1required field missing DORM_ERROR_2type mismatch DORM_ERROR_3custom validatehook threwDORM_ERROR_4not unique (app-level check on uniquefields, on create & update)DoesNotExist/MultipleObjectsReturned— thrown byget()when a query matches zero or more than one document.