---
title: "Single Document Patch Operations"
url: "https://docs.ravendb.net/6.2/client-api/operations/patching/single-document"
version: "6.2"
language: "nodejs"
---

# Single Document Patch Operations

> Client language: Node.js. Also available for [C#](https://docs.ravendb.net/6.2/client-api/operations/patching/single-document.md), [Java](https://docs.ravendb.net/6.2/client-api/operations/patching/single-document.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**
>
> - Patching allows **updating only parts of a document** in a single trip to the server,  
>   without having to load, modify, and save the entire document back to the database.
>
> - This is particularly efficient for large documents or when only a small portion of the document needs to be changed,
>   reducing the amount of data transferred over the network.
>
> - The patching operation is executed on the server-side within a [Single write transaction](https://docs.ravendb.net/6.2/client-api/faq/transaction-support.md).
>
> - This article covers patch operations on single documents from the Client API.  
>   To patch multiple documents that match certain criteria see [Set based patching](https://docs.ravendb.net/6.2/client-api/operations/patching/set-based.nodejs.md).  
>   Patching can also be done from the [Studio](https://docs.ravendb.net/6.2/studio/database/documents/patch-view.md).
>
> - In this page:
>
>   - [API overview](#api-overview)
>
>   - [Examples](#examples)
>     - [Modify value of single field](#modify-value-of-single-field)
>     - [Modify values of two fields](#modify-values-of-two-fields)
>     - [Increment value](#increment-value)
>     - [Add or increment](#add-or-increment)
>     - [Add or patch](#add-or-patch)
>     - [Add item to array](#add-item-to-array)
>     - [Add or patch an existing array](#add-or-patch-an-existing-array)
>     - [Insert item into specific position in array](#insert-item-into-specific-position-in-array)
>     - [Modify item in specific position in array](#modify-item-in-specific-position-in-array)
>     - [Remove items from array](#remove-items-from-array)
>     - [Load documents in a script](#load-documents-in-a-script)
>     - [Remove property](#remove-property)
>     - [Rename property](#rename-property)
>     - [Add document](#add-document)
>     - [Clone document](#clone-document)
>     - [Create/Increment counter](#createincrement-counter)
>     - [Delete counter](#delete-counter)
>     - [Get counter](#get-counter)
>     - [Patching using inline string compilation](#patching-using-inline-string-compilation)
>
>   - [Syntax](#syntax)
>     - [Session API syntax](#session-api-syntax)
>     - [Session API using defer syntax](#session-api-using-defer-syntax)
>     - [Operations API syntax](#operations-api-syntax)
>     - [List of script methods syntax](#list-of-script-methods-syntax)

## API overview

Patching can be performed using either of the following interfaces (detailed syntax is provided [below](#syntax)):

- **Session API**
- **Session API using defer**
- **Operations API**

> **Note**
>
> #### Session API
>
> - This interface allows performing most common patch operations.
>
> - Multiple patch methods can be defined on the [session](https://docs.ravendb.net/6.2/client-api/session/what-is-a-session-and-how-does-it-work.nodejs.md)
>   and are sent to the server for execution in a single batch (along with any other modified documents) only when calling [SaveChanges](https://docs.ravendb.net/6.2/client-api/session/saving-changes.nodejs.md).
>
> - This API includes the following patching methods (see examples [below](#examples)):
>   - `patch`
>   - `addOrPatch`
>   - `increment`
>   - `addOrIncrement`
>   - `patchArray`
>   - `addOrPatchArray`

> **Note**
>
> #### Session API using defer
>
> - Use `defer` to manipulate the patch request directly without wrapper methods.  
>   Define the patch request yourself with a **script** and optional variables.
>
> - The patch request constructs the `PatchCommandData` command,  
>   which is then added to the session using the `defer` function.
>
> - Similar to the above Session API,  
>   all patch requests done via `defer` are sent to the server for execution only when *saveChanges* is called.

> **Note**
>
> #### Operations API
>
> - [Operations](https://docs.ravendb.net/6.2/client-api/operations/what-are-operations.nodejs.md) allow performing ad-hoc requests directly on the document store **without** creating a session.
>
> - Similar to the above *defer* usage, define the patch request yourself with a script and optional variables.
>
> - The patch requests constructs the `PatchOperation`, which is sent to the server for execution only when *saveChanges* is called.

## Examples

> **Note**
>
> #### Modify value of single field
>
> ##### Session\_syntax
>
> ```javascript
> // Modify FirstName to Robert using the 'patch' method
> // ===================================================
>
> session.advanced.patch("employees/1-A", "FirstName", "Robert");        
> await session.saveChanges();
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Modify FirstName to Robert using 'defer' with 'PatchCommandData'
> // ================================================================
>
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.FirstName = args.FirstName;";
> patchRequest.values = { FirstName: "Robert" };
>       
> const patchCommand = new PatchCommandData("employees/1-A", null, patchRequest);        
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Modify FirstName to Robert via 'PatchOperation' on the documentStore
> // ====================================================================
>
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.FirstName = args.FirstName;";
> patchRequest.values = { FirstName: "Robert" };
>
> const patchOp = new PatchOperation("employees/1-A", null, patchRequest);        
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Modify values of two fields
>
> ##### Session\_syntax
>
> ```javascript
> // Modify FirstName to Robert and LastName to Carter in single request
> // ===================================================================
>
> // The two Patch operations below are sent via 'saveChanges()' which complete transactionally,
> // as this call generates a single HTTP request to the database. 
> // Either both will succeed - or both will be rolled back - since they are applied within the same
> // transaction.
>
> // However, on the server side, the two Patch operations are still executed separately.
> // To achieve atomicity at the level of a single server-side operation, use 'defer' or an 'operation'.
>
> session.advanced.patch("employees/1-A", "FirstName", "Robert");
> session.advanced.patch("employees/1-A", "LastName", "Carter");
>
> await session.saveChanges();
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Modify FirstName to Robert and LastName to Carter in single request
> // ===================================================================
>
> // Note that here we do maintain the operation's atomicity
> const patchRequest = new PatchRequest();
> patchRequest.script = `this.FirstName = args.FirstName;
>                      this.LastName = args.LastName;`;
> patchRequest.values = { 
>   FirstName: "Robert",
>   LastName: "Carter"
> };
>
> const patchCommand = new PatchCommandData("employees/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Modify FirstName to Robert and LastName to Carter in single request
> // ===================================================================
>
> // Note that here we do maintain the operation's atomicity
> const patchRequest = new PatchRequest();
> patchRequest.script = `this.FirstName = args.FirstName;
>                      this.LastName = args.LastName;`;
> patchRequest.values = {
>   FirstName: "Robert",
>   LastName: "Carter"
> };
>
> const patchOp = new PatchOperation("employees/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Increment value
>
> ##### Session\_syntax
>
> ```javascript
> // Increment UnitsInStock property value by 10
> // ===========================================
>
> session.advanced.increment("products/1-A", "UnitsInStock", 10);
> await session.saveChanges();
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Increment UnitsInStock property value by 10
> // ===========================================
>
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.UnitsInStock += args.UnitsToAdd;";
> patchRequest.values = {
>   UnitsToAdd: 10
> };
>
> const patchCommand = new PatchCommandData("products/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Increment UnitsInStock property value by 10
> // ===========================================
>
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.UnitsInStock += args.UnitsToAdd;";
> patchRequest.values = {
>   UnitsToAdd: 10
> };
>
> const patchOp = new PatchOperation("products/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Add or increment
>
> `addOrIncrement` behavior:
>
> - If document exists + has the specified field =>
>   - A numeric field will be **incremented** by the specified value.
>   - A string field will be **concatenated** with the specified value.
>   - The entity passed is disregarded.
> - If document exists + does Not contain the specified field =>
>   - The field will be **added** to the document with the specified value.
>   - The entity passed is disregarded.
> - If document does Not exist =>
>   - A new document will be **created** from the provided entity.
>   - The value to increment by is disregarded.
>
> ##### Session\_syntax
>
> ```javascript
> // An entity that will be used in case the specified document is not found:
> const newUser = new User();
> newUser.firstName = "John";
> newUser.lastName = "Doe";
> newUser.loginCount = 1;
>
> session.advanced.addOrIncrement(
>   // Specify document id on which the operation should be performed
>   "users/1",
>   // Specify an entity,
>   // if the specified document is Not found, a new document will be created from this entity
>   newUser,
>   // The field that should be incremented
>   "loginCount",
>   // Increment the specified field by this value
>   2);
>
> await session.saveChanges();
> ```
>
> ##### User\_class
>
> ```javascript
> class User {
>   constructor(
>       id = null,
>       firstName = "",
>       lastName = "",
>       loginCount = 0,
>       lastLogin = new Date(),
>       loginTimes = []
>   ) {
>       Object.assign(this, {
>           id,
>           firstName,
>           lastName,
>           loginCount,
>           lastLogin,
>           loginTimes
>       });
>   }
> }
> ```

> **Note**
>
> #### Add or patch
>
> `addOrPatch` behavior:
>
> - If document exists + has the specified field =>
>   - The field will be **patched**, the specified value will replace the existing value.
>   - The entity passed is disregarded.
> - If document exists + does Not contain the specified field =>
>   - The field will be **added** to the document with the specified value.
>   - The entity passed is disregarded.
> - If document does Not exist =>
>   - A new document will be **created** from the provided entity.
>   - The value to patch by is disregarded.
>
> ##### Session\_syntax
>
> ```javascript
> // An entity that will be used in case the specified document is not found:
> const newUser = new User();
> newUser.firstName = "John";
> newUser.lastName = "Doe";
> newUser.lastLogin = new Date(2024, 0, 1);
>
> session.advanced.addOrPatch(
>   // Specify document id on which the operation should be performed
>   "users/1",
>   // Specify an entity,
>   // if the specified document is Not found, a new document will be created from this entity
>   newUser,
>   // The field that should be patched
>   "lastLogin",
>   // Set the current date and time as the new value for the specified field
>   new Date());
>
> await session.saveChanges();
> ```
>
> ##### User\_class
>
> ```javascript
> class User {
>   constructor(
>       id = null,
>       firstName = "",
>       lastName = "",
>       loginCount = 0,
>       lastLogin = new Date(),
>       loginTimes = []
>   ) {
>       Object.assign(this, {
>           id,
>           firstName,
>           lastName,
>           loginCount,
>           lastLogin,
>           loginTimes
>       });
>   }
> }
> ```

> **Note**
>
> #### Add item to array
>
> `patchArray` behavior:
>
> - If document exists + has the specified array =>
>   - Item will be **added** to the array.
> - If document exists + does Not contain the specified array field =>
>   - No exception is thrown, no patching is done, a new array is Not created.
> - If document does Not exist =>
>   - No exception is thrown, no patching is done, a new document is Not created.
>
> ##### Session\_syntax
>
> ```javascript
> // Add a new comment to an array
> // =============================
>
> // The new comment to add:
> const newBlogComment = new BlogComment();
> newBlogComment.content = "Some content";
> newBlogComment.title = "Some title";
>
> // Call 'patchArray':
> session.advanced.patchArray(
>   "blogPosts/1",  // Document id to patch
>   "comments",     // The array to add the comment to
>   comments => {   // Adding the new comment
>       comments.push(newBlogComment); 
>   });
>
> await session.saveChanges();
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Add a new comment to an array
> // =============================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.comments.push(args.comment);";
> patchRequest.values = {
>   comment: {
>       title: "Some title",
>       content: "Some content",
>   }
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("blogPosts/1", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Add a new comment to an array
> // =============================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.comments.push(args.comment);";
> patchRequest.values = {
>   comment: {
>       title: "Some title",
>       content: "Some content",
>   }
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("blogPosts/1", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```
>
> ##### Blog\_classes
>
> ```javascript
> class BlogPost {
>   constructor(
>       id = null,
>       title = "",
>       body = "",
>       comments = []
>   ) {
>       Object.assign(this, {
>           id,
>           title,
>           body,
>           comments
>       });
>   }
> }
>
> class BlogComment {
>   constructor(
>       title = "",
>       content = ""
>   ) {
>       Object.assign(this, {
>           title,
>           content
>       });
>   }
> }
> ```

> **Note**
>
> #### Add or patch an existing array
>
> `addOrPatchArray` behavior:
>
> - If document exists + has the specified array field =>
>   - The specified values will be **added** to the existing array values.
>   - The entity passed is disregarded.
> - If document exists + does Not contain the specified array field =>
>   - The array field is Not added to the document, no patching is done.
>   - The entity passed is disregarded.
> - If document does Not exist =>
>   - A new document will be **created** from the provided entity.
>   - The value to patch by is disregarded.
>
> ##### Session\_syntax
>
> ```javascript
> // An entity that will be used in case the specified document is not found:
> const newUser = new User();
> newUser.firstName = "John";
> newUser.lastName = "Doe";
> newUser.loginTimes = [new Date(2024, 0, 1)];
>
> session.advanced.addOrPatchArray(
>   // Specify document id on which the operation should be performed
>   "users/1",
>   // Specify an entity,
>   // if the specified document is Not found, a new document will be created from this entity
>   newUser,
>   // The array field that should be patched
>   "loginTimes",
>   // Add values to the list of the specified array field
>   a => a.push(new Date(2024, 2, 2), new Date(2024, 3, 3)));
>
> await session.saveChanges();
> ```
>
> ##### User\_class
>
> ```javascript
> class User {
>   constructor(
>       id = null,
>       firstName = "",
>       lastName = "",
>       loginCount = 0,
>       lastLogin = new Date(),
>       loginTimes = []
>   ) {
>       Object.assign(this, {
>           id,
>           firstName,
>           lastName,
>           loginCount,
>           lastLogin,
>           loginTimes
>       });
>   }
> }
> ```

> **Note**
>
> #### Insert item into specific position in array
>
> - Inserting an item in a specific position is supported only by the *defer* or the *operations* syntax.
> - No exception is thrown if either the document or the specified array does not exist.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Insert a new comment at position 1
> // ==================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.comments.splice(1, 0, args.comment);";
> patchRequest.values = {
>   comment: {
>       title: "Some title",
>       content: "Some content",
>   }
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("blogPosts/1", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Insert a new comment at position 1
> // ==================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.comments.splice(1, 0, args.comment);";
> patchRequest.values = {
>   comment: {
>       title: "Some title",
>       content: "Some content",
>   }
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("blogPosts/1", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```
>
> ##### Blog\_classes
>
> ```javascript
> class BlogPost {
>   constructor(
>       id = null,
>       title = "",
>       body = "",
>       comments = []
>   ) {
>       Object.assign(this, {
>           id,
>           title,
>           body,
>           comments
>       });
>   }
> }
>
> class BlogComment {
>   constructor(
>       title = "",
>       content = ""
>   ) {
>       Object.assign(this, {
>           title,
>           content
>       });
>   }
> }
> ```

> **Note**
>
> #### Modify item in specific position in array
>
> - Inserting an item in a specific position is supported only by the *defer* or the *operations* syntax.
> - No exception is thrown if either the document or the specified array does not exist.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Modify comment at position 3
> // ============================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.comments.splice(3, 1, args.comment);";
> patchRequest.values = {
>   comment: {
>       title: "Some title",
>       content: "Some content",
>   }
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("blogPosts/1", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Modify comment at position 3
> // ============================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = "this.comments.splice(3, 1, args.comment);";
> patchRequest.values = {
>   comment: {
>       title: "Some title",
>       content: "Some content",
>   }
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("blogPosts/1", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```
>
> ##### Blog\_classes
>
> ```javascript
> class BlogPost {
>   constructor(
>       id = null,
>       title = "",
>       body = "",
>       comments = []
>   ) {
>       Object.assign(this, {
>           id,
>           title,
>           body,
>           comments
>       });
>   }
> }
>
> class BlogComment {
>   constructor(
>       title = "",
>       content = ""
>   ) {
>       Object.assign(this, {
>           title,
>           content
>       });
>   }
> }
> ```

> **Note**
>
> #### Remove items from array
>
> - Removing all items that match some predicate from an array is supported only by the *defer* or the *operations* syntax.
> - No exception is thrown if either the document or the specified array does not exist.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Remove all comments that contain the word "wrong" in their content
> // ==================================================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `this.comments = this.comments.filter(comment => 
>                      !comment.content.includes(args.text));`;
> patchRequest.values = {
>   text: "wrong"
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("blogPosts/1", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Remove all comments that contain the word "wrong" in their content
> // ==================================================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `this.comments = this.comments.filter(comment => 
>                      !comment.content.includes(args.text));`;
> patchRequest.values = {
>   text: "wrong"
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("blogPosts/1", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```
>
> ##### Blog\_classes
>
> ```javascript
> class BlogPost {
>   constructor(
>       id = null,
>       title = "",
>       body = "",
>       comments = []
>   ) {
>       Object.assign(this, {
>           id,
>           title,
>           body,
>           comments
>       });
>   }
> }
>
> class BlogComment {
>   constructor(
>       title = "",
>       content = ""
>   ) {
>       Object.assign(this, {
>           title,
>           content
>       });
>   }
> }
> ```

> **Note**
>
> #### Load documents in a script
>
> - Loading documents is supported only by the *defer* or the *operations* syntax.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Load a related document and update a field
> // ==========================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `this.Lines.forEach(line => { 
>                          const productDoc = load(line.Product);
>                          line.ProductName = productDoc.Name;
>                      });`;
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("orders/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Load a related document and update a field
> // ==========================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `this.Lines.forEach(line => { 
>                          const productDoc = load(line.Product);
>                          line.ProductName = productDoc.Name;
>                      });`;
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("orders/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Remove property
>
> - Removing a property is supported only by the *defer* or the *operations* syntax.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Remove a document property
> // ==========================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `delete this.Address.PostalCode;`;
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("employees/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Remove a document property
> // ==========================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `delete this.Address.PostalCode;`;
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("employees/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Rename property
>
> - Renaming a property is supported only by the *defer* or the *operations* syntax.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Rename property Name to ProductName
> // ===================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `const propertyValue = this[args.currentProperty];
>                      delete this[args.currentProperty];
>                      this[args.newProperty] = propertyValue;`;
> patchRequest.values = {
>   currentProperty: "Name",
>   newProperty: "ProductName"
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("products/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Rename property Name to ProductName
> // ===================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
> patchRequest.script = `const propertyValue = this[args.currentProperty];
>                      delete this[args.currentProperty];
>                      this[args.newProperty] = propertyValue;`;
> patchRequest.values = {
>   currentProperty: "Name",
>   newProperty: "ProductName"
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("products/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Add document
>
> - Adding a new document is supported only by the *defer* or the *operations* syntax.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Add a new document
> // ==================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Add a new document (projects/1) to collection Projects
> // The id of the patched document (employees/1-A) is used as content for ProjectLeader property
> patchRequest.script = `put('projects/1', { 
>                          ProjectLeader: id(this),
>                          ProjectDesc: 'Some desc..', 
>                          '@metadata': { '@collection': 'Projects'} 
>                      });`;
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("employees/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Add a new document
> // ==================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Add a new document (projects/1) to collection Projects
> // The id of the patched document (employees/1-A) is used as content for ProjectLeader property
> patchRequest.script = `put('projects/1', { 
>                          ProjectLeader: id(this),
>                          ProjectDesc: 'Some desc..', 
>                          '@metadata': { '@collection': 'Projects'} 
>                      });`;
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("employees/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Clone document
>
> - Cloning a new document is supported only by the *defer* or the *operations* syntax.
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Clone a document
> // ================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // The new document will be in the same collection as 'employees/1-A'
> // By specifying 'employees/' the server will generate a "server-side ID' to the new document
> patchRequest.script = `put('employees/', this);`;
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("employees/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Clone a document
> // ================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // The new document will be in the same collection as 'employees/1-A'
> // By specifying 'employees/' the server will generate a "server-side ID' to the new document
> patchRequest.script = `put('employees/', this);`;
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("employees/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```
>
> > **Info**
> >
> > **Attachments, Counters, Time Series, and Revisions:**
> >
> > - When cloning a document via patching, only the document's fields are copied to the new document.
> >   Attachments, counters, time series data, and revisions from the source document will Not be copied automatically.
> > - To manage time series & counters via patching, you can use the pre-defined JavaScript methods listed here:
> >   [Counters methods](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md#counter-operations) & [Time series methods](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md#time-series-operations).
> > - Note: When [Cloning a document via the Studio](https://docs.ravendb.net/6.2/studio/database/documents/create-new-document.md#clone-an-existing-document),
> >   attachments, counters, time Series, and revisions will be copied automatically.
> >
> > **Archived documents:**
> >
> > - If the source document is archived, the cloned document will Not be archived.

> **Note**
>
> #### Create/Increment counter
>
> ##### Session\_syntax
>
> ```javascript
> // Increment/Create counter
> // ========================
>
> // Increase counter "Likes" by 10, or create it with a value of 10 if it doesn't exist
> session.countersFor("products/1-A").increment("Likes", 10);
> await session.saveChanges();
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Create/Increment counter
> // ========================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Use the 'incrementCounter' method to create/increment a counter 
> patchRequest.script = `incrementCounter(this, args.counterName, args.counterValue);`;
> patchRequest.values = {
>   counterName: "Likes",
>   counterValue: 10
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("products/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Create/Increment counter
> // ========================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Use the 'incrementCounter' method to create/increment a counter 
> patchRequest.script = `incrementCounter(this, args.counterName, args.counterValue);`;
> patchRequest.values = {
>   counterName: "Likes",
>   counterValue: 10
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("products/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```
>
> > **Info**
> >
> > Learn more about Counters in this [Counters Overview](https://docs.ravendb.net/6.2/document-extensions/counters/overview.nodejs.md).

> **Note**
>
> #### Delete counter
>
> ##### Session\_syntax
>
> ```javascript
> // Delete counter
> // ==============
>
> session.countersFor("products/1-A").delete("Likes");
> await session.saveChanges();
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Delete counter
> // ==============
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Use the 'deleteCounter' method to delete a counter 
> patchRequest.script = `deleteCounter(this, args.counterName);`;
> patchRequest.values = {
>   counterName: "Likes"
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("products/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Delete counter
> // ==============
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Use the 'deleteCounter' method to delete a counter 
> patchRequest.script = `deleteCounter(this, args.counterName);`;
> patchRequest.values = {
>   counterName: "Likes"
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("products/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Get counter
>
> ##### Session\_syntax
>
> ```javascript
> // Get counter value
> // =================
>
> const counters = await session.counterFor("products/1-A").get("Likes");
> ```
>
> ##### Session\_defer\_syntax
>
> ```javascript
> // Get counter value
> // =================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Use the 'counter' method to get the value of the specified counter 
> // and then put the results into a new document 'productLikes/'
> patchRequest.script = `const numberOfLikes = counter(this, args.counterName);
>                      put('productLikes/', {ProductName: this.Name, Likes: numberOfLikes});`;
>
> patchRequest.values = {
>   counterName: "Likes"
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("products/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
> ```
>
> ##### Operations\_syntax
>
> ```javascript
> // Get counter value
> // =================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Use the 'counter' method to get the value of the specified counter 
> // and then put the results into a new document 'productLikes/'
> patchRequest.script = `const numberOfLikes = counter(this, args.counterName);
>                      put('productLikes/', {ProductName: this.Name, Likes: numberOfLikes});`;
>
> patchRequest.values = {
>   counterName: "Likes"
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("products/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
> ```

> **Note**
>
> #### Patching using inline string compilation
>
> - When using a JavaScript script with the *defer* or *operations* syntax,  
>   you can apply logic using **inline string compilation**.
> - To enable this, set the [Patching.AllowStringCompilation](https://docs.ravendb.net/6.2/server/configuration/patching-configuration.md#patchingallowstringcompilation) configuration key to *true*.
>
> ##### Patching\_usingFunction
>
> ```javascript
> // Modify value using inline string compilation
> // ============================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Define the script:
> patchRequest.script = `
>   // Give a discount if the product is low in stock:
>   const functionBody = "return doc.UnitsInStock < lowStock ? " + 
>       "doc.PricePerUnit * discount :" + 
>       "doc.PricePerUnit;";
>
>   // Define a function that processes the document and returns the price:
>   const calcPrice = new Function("doc", "lowStock", "discount", functionBody);
>
>   // Update the product's PricePerUnit based on the function:
>   this.PricePerUnit = calcPrice(this, args.lowStock, args.discount);`;
>
> patchRequest.values = {
>   discount: "0.8",
>   lowStock: "10"
> };
>
> // Define the 'PatchCommandData':
> const patchCommand = new PatchCommandData("products/1-A", null, patchRequest);
> session.advanced.defer(patchCommand);
>
> await session.saveChanges();
>
> // The same can be applied using the 'operations' syntax.
> ```
>
> ##### Patching\_usingEval
>
> ```javascript
> // Modify value using inline string compilation
> // ============================================
>
> // Define the 'PatchRequest':
> const patchRequest = new PatchRequest();
>
> // Define the script:
> patchRequest.script = `
>   // Give a discount if the product is low in stock:
>   const discountExpression = "this.UnitsInStock < args.lowStock ? " + 
>       "this.PricePerUnit * args.discount :" + 
>       "this.PricePerUnit";
>   
>   // Call 'eval', pass the string expression that contains your logic:
>   const price = eval(discountExpression);
>   
>   // Update the product's PricePerUnit:
>   this.PricePerUnit = price;`;
>
> patchRequest.values = {
>   discount: "0.8",
>   lowStock: "10"
> };
>
> // Define and send the 'PatchOperation':
> const patchOp = new PatchOperation("products/1-A", null, patchRequest);
> await documentStore.operations.send(patchOp);
>
> // The same can be applied using the 'session defer' syntax.
> ```

## Syntax

### Session API syntax

```javascript
patch(id, path, value);
patch(entity, path, value);
```

| Parameter | Type | Description |
| - | - | - |
| **id** | `string` | Document ID on which patching should be performed. |
| **entity** | `object` | Entity on which patching should be performed. The entity should be one that was returned by the current session in a `load` or `query` operation. |
| **Path** | `string` | The path to the field. |
| **value** | `object` | Value to set. |

```javascript
addOrPatch(id, entity, pathToObject, value);
```

| Parameter | Type | Description |
| - | - | - |
| **id** | `string` | Document ID on which patching should be performed. |
| **entity** | `object` | If the specified document is Not found, a new document will be created from this entity. |
| **Path** | `string` | The path to the field. |
| **value** | `object` | Value to set. |

```javascript
increment(id, path, valueToAdd);
increment(entity, path, valueToAdd);
```

| Parameter | Type | Description |
| - | - | - |
| **id** | `string` | Document ID on which patching should be performed. |
| **entity** | `object` | Entity on which patching should be performed. The entity should be one that was returned by the current session in a `load` or `query` operation. |
| **path** | `string` | The path to the field. |
| **valueToAdd** | `object` | Value to increment by.<br />Note how numbers are handled with the [JavaScript engine](https://docs.ravendb.net/6.2/server/kb/numbers-in-ravendb.md) in RavenDB. |

```javascript
addOrIncrement(id, entity, pathToObject, valToAdd);
```

| Parameter | Type | Description |
| - | - | - |
| **id** | `string` | Document ID on which patching should be performed. |
| **entity** | `object` | If the specified document is Not found, a new document will be created from this entity. |
| **path** | `string` | The path to the field. |
| **valueToAdd** | `object` | Value to increment by. |

```javascript
patchArray(id, pathToArray, arrayAdder);
patchArray(entity, pathToArray, arrayAdder);
```

| Parameter | Type | Description |
| - | - | - |
| **id** | `string` | Document ID on which patching should be performed. |
| **entity** | `object` | Entity on which patching should be performed. The entity should be one that was returned by the current session in a `load` or `query` operation. |
| **pathToArray** | `string` | The path to the array field. |
| **arrayAdder** | `(JavaScriptArray) => void` | Function that modifies the array. |

```javascript
addOrPatchArray(id, entity, pathToObject, arrayAdder);
```

| Parameter | Type | Description | |
| - | - | - | - |
| **id** | `string` | Document ID on which patching should be performed. | |
| **entity** | `object` | If the specified document is Not found, a new document will be created from this entity. | |
| **pathToArray** | `string` | The path to the array field. | |
| **arrayAdder** | `(JavaScriptArray) => void` | Function that modifies the array. | |

```javascript
class JavaScriptArray {
  push(...u);      // Add a list of values to add to the array
  removeAt(index); // Remove an item from position 'index' in the array
}
```

### Session API using defer syntax

```javascript
session.advanced.defer(...commands);
```

| Parameter | Type | Description |
| - | - | - |
| **commands** | `object[]` | List of commands that will be executed on the server.<br />Use the `PatchCommandData` command for patching. |

```javascript
class PatchCommandData {
  // ID of document to be patched
  id; // string
  
  // Change vector of document to be patched, can be null.
  // Used to verify that the document was not changed before the patch is executed.
  changeVector // string;
  
  // Patch request to be performed on the document
  patch; // A PatchRequest object
  
  // Patch request to perform if no document with the specified ID was found
  patchIfMissing; // A PatchRequest object
}
```

```javascript
class PatchRequest {
  //  The JavaScript code to be run on the server
  script; // string
  
  // Parameters to be passed to the script
  values:; // Dictionary<string, object>

  // It is highly recommend to use the script with the parameters. 
  // This allows RavenDB to cache scripts and boost performance.
  // The parameters are accessed in the script via the `args` object.
}
```

### Operations API syntax

- Learn more about using operations in this [Operations overview](https://docs.ravendb.net/6.2/client-api/operations/what-are-operations.nodejs.md).

```javascript
const patchOperation = new PatchOperation(id, changeVector, patch);

const patchOperation = new PatchOperation(id, changeVector, patch, patchIfMissing,
  skipPatchIfChangeVectorMismatch);
```

| Constructor | Type | Description |
| - | - | - |
| **id** | `string` | ID of the document to be patched. |
| **changeVector** | `string` | Change vector of the document to be patched.<br />Used to verify that the document was not modified before the patch is executed. Can be null. |
| **patch** | `PatchRequest` | Patch request to perform on the document. |
| **patchIfMissing** | `PatchRequest` | Patch request to perform if the specified document is not found.<br />Will run only if no `changeVector` was passed.<br />Can be null. |
| **skipPatchIfChangeVectorMismatch** | `boolean` | `true` - do not patch if the document has been modified.<br />`false` (Default) - execute the patch even if document has been modified.<br /><br />An exception is thrown if:<br />this param is `false` + `changeVector` has value + document with that ID and change vector was not found. |

### List of script methods syntax

- For a complete list of JavaScript methods available in patch scripts,  
  refer to [Knowledge Base: JavaScript Engine](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md#predefined-javascript-functions).

## See also

- [Set based patch operation](https://docs.ravendb.net/6.2/client-api/operations/patching/set-based.nodejs.md)
- [JavaScript engine](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md)
- [Numbers in JavaScript engine](https://docs.ravendb.net/6.2/server/kb/numbers-in-ravendb.md#numbers-in-javascript-engine)
