---
title: "Data subscriptions: Revisions support"
description: "Subscribe to a collection's document revisions instead of its documents, so a worker receives consecutive revision pairs and can filter and project over the changes."
url: "https://docs.ravendb.net/7.2/data-subscriptions/revisions-support"
version: "7.2"
language: "nodejs"
---

# Data subscriptions: Revisions support

> Client language: Node.js. Also available for [C#](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md), [Java](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.java.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - When the [Revisions feature](https://docs.ravendb.net/7.2/document-extensions/revisions/overview.nodejs.md) is enabled, a
>   revision is created with each change made in a document.  
>   Each revision is a snapshot of the document at the time of the change. Over time, a complete
>   audit trail is formed.
>
> - A data subscription can subscribe not only to documents but also to their revisions, allowing workers
>   to track the changes made in documents over time.
>
> - To subscribe to revisions, create the subscription using `createForRevisions`,
>   or add `(Revisions = true)` to the subscription's RQL query.
>
> - In this article:
>   - [Regular subscription vs revisions subscription](#regular-subscription-vs-revisions-subscription)
>   - [Revisions processing order](#revisions-processing-order)
>   - [Creating and consuming a revisions subscription](#creating-and-consuming-a-revisions-subscription)
>   - [Filtering revisions](#filtering-revisions)
>   - [Projecting fields from revisions](#projecting-fields-from-revisions)
>   - [Including related documents](#including-related-documents)
>   - [Reading a revision's metadata](#reading-a-revision-s-metadata)
>   - [Syntax](#syntax)

## Regular subscription vs revisions subscription {#regular-subscription-vs-revisions-subscription}

A subscription can target a collection's documents or their revisions. The two behave differently
in what they process, what the server-side query can see, and what reaches the worker.

### Regular subscription

- **Processed items**  
  The subscription selects documents from the defined collection. Only the current version of
  each document is selected, even if the document has revisions.
- **Query access scope**  
  The subscription query running on the server has access only to the current version of each document.
- **Data sent to the worker**  
  Each item in the batch contains a single document, or a projection of it, as defined in the subscription.

### Revisions subscription

- **Processed items**  
  The subscription selects all revisions of documents from the defined collection, including
  revisions of deleted documents from the revisions bin if they have not been purged.
- **Query access scope**  
  For each revision, the subscription query running on the server has access to both the revision
  being processed and its preceding revision, so it can compare the two revisions and act on what
  changed between them.
- **Data sent to the worker**  
  Unless the query [projects specific fields](#projecting-fields-from-revisions),
  each item in the batch contains both the processed revision (`result.current`) and its preceding
  revision (`result.previous`).  
  One of the two fields is `null` in these cases:
  - For a document's first revision, `result.previous` is `null`.
  - For the revision created when the document is deleted, `result.current` is `null`.

> **Warning**
>
> - For a revisions subscription to work, [Revisions must be configured](https://docs.ravendb.net/7.2/document-extensions/revisions/overview.nodejs.md#defining-a-revisions-configuration)
>   and enabled for the collection the subscription targets.
>
> - A document that has no revisions is not processed, so make sure your revisions configuration does
>   not purge revisions before the subscription has had a chance to process them.
>
> - A revisions subscription **ignores** the [processing behavior for archived documents](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.nodejs.md#archived-documents)
>   and selects the revisions of archived and non-archived documents alike.

## Revisions processing order {#revisions-processing-order}

In a revisions subscription, the worker receives revisions in consecutive pairs: each revision
together with the one immediately before it.  
This gives the worker, and the subscription query, the document's state both before and after every
change, so they can detect what changed and act on it, for example to filter or project by the difference.

For example, take this `User` document:

```json
{
    "Name": "James",
    "Age": "21"
}
```

Suppose its `Age` field is then updated twice, first to `22` and then to `23`. The worker receives
three batch items, each pairing a revision with the one before it:

| Batch item | Previous | Current |
| - | - | - |
| item #1 | `null` | `{ Name: "James", Age: "21" }` |
| item #2 | `{ Name: "James", Age: "21" }` | `{ Name: "James", Age: "22" }` |
| item #3 | `{ Name: "James", Age: "22" }` | `{ Name: "James", Age: "23" }` |

The first item pairs the document's creation with a `null` previous. Each later item carries the
earlier revision as `previous` and the next as `current`.

## Creating and consuming a revisions subscription {#creating-and-consuming-a-revisions-subscription}

This basic revisions subscription delivers to the worker pairs of consecutive `Order` revisions.

#### Example: Creating the subscription

##### Generic API

```javascript
const subscriptionName = await documentStore.subscriptions.createForRevisions({
    // Set the collection whose revisions are processed
    documentType: Order
});
```

##### RQL

```javascript
const subscriptionName = await documentStore.subscriptions.create({
    // Add (Revisions = true) to the subscription's RQL
    query: "from Orders (Revisions = true)"
});
```

#### Example: Consuming the subscription

```javascript
const workerOptions = { subscriptionName };

const revisionsWorker =
    // Use getSubscriptionWorkerForRevisions to receive revision pairs
    documentStore.subscriptions.getSubscriptionWorkerForRevisions(workerOptions);

revisionsWorker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            // The preceding revision (null for a document's first revision)
            const previousRevision = item.result.previous;

            // The revision being processed
            const currentRevision = item.result.current;

            processOrderRevisions(previousRevision, currentRevision); // your processing logic
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

## Filtering revisions {#filtering-revisions}

This subscription sends to the worker only the revisions in which the order was shipped to Mexico.

#### Example: Creating the subscription

```javascript
const subscriptionName = await documentStore.subscriptions.create({
    // Only revisions of orders shipped to Mexico are sent to the worker
    query: `declare function isSentToMexico(doc) {
                return doc.Current.ShipTo.Country == 'Mexico'
            }

            from 'Orders' (Revisions = true) as doc
            where isSentToMexico(doc) == true`
});
```

#### Example: Consuming the subscription

```javascript
const workerOptions = { subscriptionName };

const worker =
    documentStore.subscriptions.getSubscriptionWorkerForRevisions(workerOptions);

worker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            console.log(`
                This is a revision of document ${item.id}.
                The order in this revision was shipped at ${item.result.current.ShippedAt}.`);
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

## Projecting fields from revisions {#projecting-fields-from-revisions}

This subscription filters the revisions and sends to the worker only the projected data rather than
the full revision pair.

#### Example: Creating the subscription

##### Subscription definition

```javascript
const subscriptionName = await documentStore.subscriptions.create({
    // Process only revisions whose revenue exceeds the preceding revision's by more than 2500,
    // and project the fields sent to the worker
    query: `declare function isRevenueDeltaAboveThreshold(doc, threshold) {
                return doc.Previous !== null && doc.Current.Lines.map(function(x) {
                    return x.PricePerUnit * x.Quantity;
                }).reduce((a, b) => a + b, 0) > doc.Previous.Lines.map(function(x) {
                    return x.PricePerUnit * x.Quantity;
                }).reduce((a, b) => a + b, 0) + threshold
            }

            from 'Orders' (Revisions = true) as doc
            where isRevenueDeltaAboveThreshold(doc, 2500)

            select {
                previousRevenue: doc.Previous.Lines.map(function(x) {
                    return x.PricePerUnit * x.Quantity;
                }).reduce((a, b) => a + b, 0),

                currentRevenue: doc.Current.Lines.map(function(x) {
                    return x.PricePerUnit * x.Quantity;
                }).reduce((a, b) => a + b, 0)
            }`
});
```

##### Projection class

```javascript
class OrderRevenues {
    constructor() {
        this.previousRevenue;
        this.currentRevenue;
    }
}
```

#### Example: Consuming the subscription

Because the revision fields are projected into `OrderRevenues` in the subscription's definition,
each batch item has the shape of that projected class rather than the default `result.previous` and
`result.current` fields shown in the
[simple example](#creating-and-consuming-a-revisions-subscription).

```javascript
const workerOptions = {
    subscriptionName,
    // Use the projected class as the item type, so use getSubscriptionWorker (not ...ForRevisions)
    documentType: OrderRevenues
};

const revenuesComparisonWorker =
    documentStore.subscriptions.getSubscriptionWorker(workerOptions);

revenuesComparisonWorker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            console.log(`
                Revenue for order ${item.id}
                grew from ${item.result.previousRevenue}
                to ${item.result.currentRevenue}`);
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

## Including related documents {#including-related-documents}

A revisions subscription can include related documents in the batches it sends (e.g., the `Employee` document that an order's
`Employee` field refers to), so the worker can read these documents without requesting them from the server.  
The path of each include starts at the revision being processed (`Current`) or at the preceding revision (`Previous`), and ends at
the field that holds the ID of the document to include, e.g., `doc.Current.Employee` (where `doc` is the query's alias).  
The worker reads an included document by loading the document in a session opened using `batch.openSession`.  
To learn more about including related documents in batches, see
[Example: Including documents in the batch](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.nodejs.md#example-including-documents-in-the-batch).

### Example

In this example, the worker reports orders that were reassigned from one employee to another, and reads the names of both employees.

#### Creating the subscription

```javascript
const subscriptionName = await documentStore.subscriptions.create({
    // Include the employees that the processed revision and the preceding revision refer to
    query: `from Orders (Revisions = true) as doc
            include doc.Current.Employee, doc.Previous.Employee`
});
```

#### Consuming the subscription

```javascript
const workerOptions = { subscriptionName };

const worker =
    documentStore.subscriptions.getSubscriptionWorkerForRevisions(workerOptions);

worker.on("batch", async (batch, callback) => {
    try {
        // Open a session using 'batch.openSession' to access the included Employee documents
        const session = batch.openSession();

        for (const item of batch.items) {
            const previousRevision = item.result.previous;
            const currentRevision = item.result.current;

            // Skip a document's first revision, the revision created when the document was deleted,
            // and revisions that did not change the employee
            if (!previousRevision || !currentRevision ||
                previousRevision.Employee === currentRevision.Employee) {
                continue;
            }

            // Calling 'load' will not generate a request to the server,
            // because both employees were included in the batch
            const previousEmployee = await session.load(previousRevision.Employee);
            const currentEmployee = await session.load(currentRevision.Employee);

            console.log(`
                Order ${item.id} was reassigned from
                ${previousEmployee.FirstName} ${previousEmployee.LastName}
                to ${currentEmployee.FirstName} ${currentEmployee.LastName}`);
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

## Reading a revision's metadata {#reading-a-revision-s-metadata}

Each batch item of a revisions subscription holds two revisions of a document (`current` and `previous`).  
The item's `metadata` property and each revision's own metadata hold these kinds of metadata properties:

- **Properties set by RavenDB** (e.g., `@id` and `@change-vector`)  
  The item's `metadata` property holds a few of these properties for the item itself.  
  Each revision's metadata holds these properties for the revision.
- **Properties you set yourself** (e.g., `trace.id`)  
  Only each revision's metadata holds these properties. The item's `metadata` property does not.

To read a revision's metadata, read the revision's `@metadata` object in the item's `rawResult` property,
which holds the item before deserialization.

e.g., the following worker reads the `trace.id` metadata property of each processed revision.

```javascript
worker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            // Read a metadata property you set yourself from the revision being processed
            // (`current` is null for the revision created when the document was deleted)
            const traceId = item.rawResult.current?.["@metadata"]["trace.id"];
            if (traceId) {
                // your processing logic here
            }
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

## Syntax {#syntax}

### Classes

The processed-item type for a revisions subscription. Each batch item's `result` is a
`Revision<T>` object holding the revision being processed and the one before it.

```javascript
interface Revision<T> {
    previous: T;
    current: T;
}
```

| Field | Type | Description |
| - | - | - |
| **previous** | `T` | The preceding revision. `null` when `current` is the document's first revision. |
| **current** | `T` | The revision being processed. `null` for the revision created when the document is deleted. |
