DEV Community

Cover image for Building a Field-Level Audit Trail with Mongoose
Mitya
Mitya

Posted on

Building a Field-Level Audit Trail with Mongoose

I built mongoose-history-audit to add an audit trail to applications that use MongoDB through Mongoose. It records field-level changes and carries the actor and execution channel through asynchronous code.

Sooner or later every project faces the same question: who changed this document, when, and what exactly? A support engineer asks why a user's tariff plan changed last Tuesday. A compliance officer asks for the history of edits to a contract. A developer debugs a bug that "the field was fine yesterday" — and needs to see every intermediate state.

There are several approaches to solving this problem:

  • Write audit code by hand in every service method — logChange(...) next to each updateOne. It works, but it is boilerplate, it is easy to forget, and it silently diverges as new endpoints appear.
  • Store a full document snapshot on every change. Complete, but heavy — most updates touch one or two fields, and you pay storage for the whole document each time. Finding "what exactly changed" then means diffing snapshots yourself.
  • Use change streams. They capture database-level changes, but application identity and request context are not automatically part of a change event. You need to correlate those separately (or use additional database features such as pre/post-images where applicable).
  • Use an existing history/versioning plugin. Depending on the library, it may store full document versions, expose limited actor/context metadata, or cover only some Mongoose write methods. Check its supported operations against the methods your application actually uses.

The solution is a Mongoose plugin that hooks supported model write operations and, when an audit context is enabled, stores a field-level diff together with who made the change and through which channel. The context is propagated across asynchronous calls with AsyncLocalStorage, so you do not have to pass the actor through every repository method.

Realization

Installing the library:

npm i mongoose-history-audit mongoose
Enter fullscreen mode Exit fullscreen mode

The package currently requires Node.js 20 or newer and supports Mongoose 8 and 9.

Then attach the plugin to a schema:

import { Schema } from 'mongoose';
import { auditTrailPlugin } from 'mongoose-history-audit';

const userSchema = new Schema({ name: String, email: String });
userSchema.plugin(auditTrailPlugin, {
    historyCollectionName: 'users_audit_history',
});
Enter fullscreen mode Exit fullscreen mode

When an audit context is enabled, supported Mongoose model writes (including save, findOneAndUpdate, findOneAndReplace, updateOne/Many, deleteOne/Many, findOneAndDelete, insertMany, and bulkWrite) produce a record in users_audit_history:

{
  "collection_name": "users",
  "model_name": "User",
  "document_id": ObjectId("..."),
  "action": "updated",
  "method": "findOneAndUpdate",
  "changes": {
    "email": { "old": "a@x.com", "new": "b@x.com" }
  },
  "modified_by": ObjectId("..."),
  "source": "http",
  "created_at": ISODate("...")
}
Enter fullscreen mode Exit fullscreen mode

Note that changes is a diff — only the fields that actually changed, with their old and new values. Values keep their original BSON types (Date, ObjectId), nothing is stringified.

Two fields in this record carry the context of the change, and they answer the questions a diff alone cannot:

  • modified_by — the id of the actor responsible for the change: an ObjectId (or a valid id string) when an actor is known, or null for an unattributed system operation such as a scheduled job or background consumer. A null value means the library was not given an actor id; it does not identify which person initiated the work.
  • source — the channel the change came through: http, graphql, ws, rpc, kafka, rabbitmq, cron, cli, or your own. The same user id can appear from different places (a web app and an admin panel), and the same null can mean very different things — source: 'cron' and source: 'kafka' are both system records, but only one of them is a scheduled job you can go look at.

Together they make a history record easier to interpret: { action: 'updated', changes: {...}, modified_by: <user>, source: 'http' } says that the change was attributed to that user and came through the HTTP channel. This reduces the need to correlate application logs, although it does not replace request-level logs or additional business metadata. Auditing only runs when an enabled audit context is active. The simplest way to open one works everywhere:

import { runWithAuditContext } from 'mongoose-history-audit';

await runWithAuditContext({ enabled: true, modifiedBy: user.id, source: 'http' }, () => repo.save(doc));
Enter fullscreen mode Exit fullscreen mode

In a NestJS app the context is opened automatically from the request — register one global interceptor and mark handlers with a decorator:

import { AuditTrail, AuditTrailInterceptor } from 'mongoose-history-audit/nest';

app.useGlobalInterceptors(app.get(AuditTrailInterceptor));

@Controller('users')
class UserController {
  @Post()
  @AuditTrail() // modifiedBy read from request.user._id ?? request.user.id ?? null
  create() { ... }
}
Enter fullscreen mode Exit fullscreen mode

In Fastify an onRequest hook covers the whole request lifecycle:

import { createAuditContextHook } from 'mongoose-history-audit/fastify';

fastify.addHook('onRequest', createAuditContextHook());

fastify.post('/users', async (req, reply) => {
    const user = await User.create(req.body);
    reply.code(201).send(user);
    // → users_audit_history: { action: 'created', modified_by: <request.user…>, source: 'http' }
});
Enter fullscreen mode Exit fullscreen mode

CLI and cron jobs

Outside HTTP there is no request and no user, so modified_by is an honest null — a system record. Two ways in; both funnel into the same core scope.

In NestJS @AuditContext wraps the handler itself, no interceptor required (default source: 'cli'):

import { AuditContext } from 'mongoose-history-audit/nest';

@AuditContext({ source: () => process.env.HISTORY_SOURCE ?? 'cron' })
@Command({ command: 'rewards:archive' })
async archive() { ... } // modified_by: null (system record)
Enter fullscreen mode Exit fullscreen mode

In a Fastify app or a vanilla Node worker call the core scope directly from the scheduled task:

import { runWithAuditContext } from 'mongoose-history-audit';

await runWithAuditContext({ enabled: true, source: 'cron' }, () => archiveRewards());
// → history: modified_by: null, source: 'cron'
Enter fullscreen mode Exit fullscreen mode

A nice pattern for reconciliation jobs: load the owner first, then open the scope with their id — the inner scope wins for every write inside it, and after it exits you are back to the system record:

const job = await Job.findOne({ type: 'guarantee-emails', status: 'pending' });

await runWithAuditContext(
    { enabled: true, modifiedBy: job.created_by, source: 'cron' }, // ← from DB
    () => dispatchGuaranteedEmails(job), // history: modified_by = job.created_by
);
Enter fullscreen mode Exit fullscreen mode

Other transports (gRPC / WebSocket / GraphQL)

In NestJS, @AuditTrail can be used across HTTP, GraphQL, RPC, and WebSocket handlers. The global interceptor reads context.getType() and builds the audit context for the transport:

Transport source default modifiedBy default
http http request.user._id ?? request.user.id ?? null
graphql graphql same, from the Apollo { req } context (resolver arg 3)
rpc (gRPC, NATS, Kafka, …) rpc null — system record
ws ws null — system record

Auth extraction is application policy, so outside HTTP the default is an honest null and the option does the work — getModifiedBy receives the whole ExecutionContext:

// gRPC — read a metadata header (Metadata.get() returns string[])
@GrpcMethod('AccountService', 'CreateAccount')
@AuditTrail({ getModifiedBy: ctx => ctx.switchToRpc().getContext()?.get('authorization')?.[0] ?? null })
handle(request) { ... }

// WebSocket — read the message or handshake
@SubscribeMessage('update')
@AuditTrail({ getModifiedBy: ctx => ctx.switchToWs().getData()?.user_id ?? null })
update() { ... }

// GraphQL — { req } comes from the Apollo context
@Mutation(() => Post)
@AuditTrail({ getModifiedBy: ctx => ctx.getArgs()[2]?.req?.user?.id ?? null })
createPost() { ... }
Enter fullscreen mode Exit fullscreen mode

An async extractor is awaited before the handler runs (getModifiedBy: async ctx => …), and the resolved value must be an ObjectId / id string — anything else is recorded as modified_by: null.

Kafka / RabbitMQ consumers

kafka and rabbitmq are built-in sources. Every Nest microservice transport reports context.getType() === 'rpc', so a @MessagePattern handler reads the id from the message — the payload (getData()) or the headers (getContext() is the transport's KafkaContext / RmqContext):

import { Ctx, MessagePattern, Payload } from '@nestjs/microservices';
import { KafkaContext, RmqContext } from '@nestjs/microservices';
import { AuditTrail } from 'mongoose-history-audit/nest';

// Kafka — headers live on the raw message
@MessagePattern('orders.created')
@AuditTrail({
  source: 'kafka',
  getModifiedBy: ctx => ctx.switchToRpc().getContext().getMessage()?.headers?.['x-user-id'] ?? null,
})
handleOrder(@Payload() order: Order, @Ctx() ctx: KafkaContext) { ... }

// RabbitMQ — headers live under properties
@MessagePattern('orders.created')
@AuditTrail({
  source: 'rabbitmq',
  getModifiedBy: ctx => ctx.switchToRpc().getContext().getMessage()?.properties?.headers?.['x-user-id'] ?? null,
})
handleOrder(@Payload() order: Order, @Ctx() ctx: RmqContext) { ... }

// id in the message body — getData() is the payload
@AuditTrail({ source: 'kafka', getModifiedBy: ctx => ctx.switchToRpc().getData()?.user_id ?? null })
handleBodyOrder() { ... }
Enter fullscreen mode Exit fullscreen mode

A consumer outside Nest (kafka.js / amqplib) opens the core scope around the handler instead — no interceptor involved:

import { runWithAuditContext } from 'mongoose-history-audit';

kafka.on('message', message =>
    runWithAuditContext({ enabled: true, modifiedBy: message.headers['x-user-id'], source: 'kafka' }, () => handleMessage(message)),
);
// → history: modified_by = <header id>, source: 'kafka'
Enter fullscreen mode Exit fullscreen mode

The source field is how you later tell apart "a user did this via HTTP" from "a nightly job" or "a consumer processed a message". Built-in channels (http, cron, cli, rabbitmq, kafka, rpc, ws, graphql) are pre-registered; custom ones must be registered once at startup — an unknown value throws instead of being silently recorded:

import { registerAuditSources } from 'mongoose-history-audit';

registerAuditSources('nats', 'grpc');
Enter fullscreen mode Exit fullscreen mode

How it works

For this approach to work, the plugin wraps every write in a snapshot → change → diff cycle:

mongoose write (save / update / delete / bulkWrite)
        │
        ▼
1. pre-hook: snapshot the old state (same session as the write)
2. the data change is applied
3. post-hook: re-read / use the result, diff old vs new
        │
        ▼
insert into the history collection
(same transaction as the data change, if any)
Enter fullscreen mode Exit fullscreen mode

So an updateOne that flips one field produces exactly one field in changes:

await User.updateOne({ _id }, { $set: { email: 'b@x.com' } });
// → { action: 'updated', changes: { email: { old: 'a@x.com', new: 'b@x.com' } } }
Enter fullscreen mode Exit fullscreen mode

The plugin also accepts a metadata option for adding application-defined fields to a history record (for example, request or job metadata).

A few diff details worth knowing:

  • Subdocument arrays with _id shrink to only the elements that changed — an added element shows up as { old: [], new: [ ... ] }, a modified one as one version per side. A pure reorder falls back to the full array on both sides, since order is part of the value.
  • __v, root _id, and timestamp fields are excluded from changes by default. The omitPaths option extends this and reaches the optional old_document / current_document snapshots (diffOnly: false) too — so a field you omit (a secret, a token) is not stored anywhere in the history record.
  • A save that changes nothing writes no record.

Supported operations and operational considerations

The plugin currently supports save, findOneAndUpdate, findOneAndReplace, updateOne, updateMany, deleteOne, deleteMany, findOneAndDelete, insertMany, and Model.bulkWrite. Direct collection/driver calls and aggregation pipelines that write through $out or $merge are outside the hook-based coverage.

An audit trail can contain sensitive data: by default, changes stores old and new field values. Use omitPaths for secrets and tokens, review the diffOnly: false snapshot option carefully, and apply appropriate access controls and retention policies to the history collection. An audit log is not automatically tamper-proof or a complete compliance solution.

Snapshotting documents and writing history adds database work. Pay particular attention to high-volume writes and to updateMany / deleteMany: maxSnapshotDocuments (default 5000) limits the number of matched documents snapshotted. If an operation exceeds that limit, the history is not a complete record of every matched document.

Transactions

When the operation runs with a session, the plugin joins it: snapshot reads and the history insert use the same session as the data change. With an active transaction, data and history commit together or roll back together. This depends on the operation actually receiving a session; connection.transaction() requires Mongoose's transactionAsyncLocalStorage opt-in unless you pass a session explicitly.

mongoose.set('transactionAsyncLocalStorage', true);

await connection.transaction(async () => {
    await User.updateOne({ _id }, { $set: { status: 'banned' } });
});
// commit → the data change AND its history record are both in
// rollback → neither is
Enter fullscreen mode Exit fullscreen mode

Two behaviors follow from this:

  • A history failure inside an active transaction is rethrown — the caller's transaction aborts, because a data change without its audit record is not acceptable.
  • Outside a transaction the data change has already been applied, so a history failure is logged and swallowed — the alternative would be throwing away a successful write.

Note the transactionAsyncLocalStorage opt-in above: without it (or an explicit session) the plugin sees no session and writes history outside the transaction, so it is no longer atomic. That is a Mongoose opt-in, not a plugin default.

Limitations

A few boundaries worth knowing about:

  • Only supported Mongoose model operations are tracked. Direct driver writes such as collection.insertOne(...) and aggregations with $out / $merge bypass Mongoose hooks. The plugin does not provide database-wide auditing: writes made outside the supported Mongoose APIs are not captured.
  • modifiedBy must be an id (an ObjectId or a valid id string) or null. It is not a lazy resolver — passing a function fails validation and is silently recorded as null.
  • A global NestJS interceptor makes the app-wide resolver moot. The interceptor opens a scope for every request (and a scope always wins), so setAuditContextResolver() is never consulted during request handling — read your CLS store in the decorator instead. The resolver is for apps without an interceptor/hook, or for work outside HTTP.
  • updateMany / deleteMany snapshot matched documents up to maxSnapshotDocuments (default: 5000). This protects against unexpectedly large snapshots, but it also means a bulk operation matching more than the cap will not have a complete per-document audit trail. Treat the cap as a completeness boundary, not just a performance setting.

Summary

An audit trail built this way gives you:

  • field-level change history for supported Mongoose model writes, provided an enabled audit context is active
  • subdocument array mutations tracked element-by-element — added, removed and modified items show up as exactly those elements in the diff, not as a full array rewrite
  • modified_by — who changed the data — without threading the user through every repository call
  • source — through which channel — so a nightly job, a Kafka consumer, and an HTTP user action are never confused; works the same across HTTP, gRPC, WebSocket, GraphQL, Kafka, RabbitMQ, cron and CLI
  • transaction atomicity when the write runs in a session and the history insert joins that transaction
  • zero runtime dependencies

If you find this solution useful, I'd appreciate a GitHub star! 😊

Top comments (0)