Course contentsShow
← Node.js
Lesson 855 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Audit Logging in NoSQL

You will capture history in append-only logs for immutable documentation.

In this lesson, you will learn how to create an immutable history of document changes using append-only audit logs in a NoSQL database.

Why Audit Logging?

In a typical NoSQL document, we often perform "in-place" updates—for example, changing a user’s status from active to suspended. While this is efficient, it destroys the history of what that status was before. For regulatory compliance, debugging, or user transparency, we need a way to track the evolution of our data without overwriting the past.

The Append-Only Strategy

The most effective pattern in NoSQL for this is the Append-Only Log. Instead of modifying a document and hoping to remember what changed, we create a secondary collection (e.g., audit_logs) where we "push" a record every time a critical action occurs. We never update or delete these log entries; we only insert them.

Imagine an orders collection. Every time an order status changes, we insert a document into our audit_logs collection:

// Example of an audit log entry
const auditEntry = {
  orderId: "ord_123",
  action: "STATUS_CHANGE",
  previousValue: "pending",
  newValue: "shipped",
  changedBy: "admin_user_01",
  timestamp: new Date()
};

// Always insert, never update
await db.collection('audit_logs').insertOne(auditEntry);

Why this works

By keeping these logs separate from the primary data, we ensure our main collection stays performant while building a permanent, immutable ledger. Because NoSQL databases handle high-volume inserts exceptionally well, this does not create the same contention issues you might see in traditional SQL systems. Even if a user updates their profile ten times, your audit_logs collection simply grows linearly, providing a perfect "paper trail" for every change that has occurred since the document’s inception.

When you need to see the history of a document, you simply query the audit_logs collection with a filter like { orderId: "ord_123" } and sort by timestamp.

Key Takeaway: Never overwrite history; instead, use an append-only collection to capture a chronological, immutable ledger of all document transitions.