Single Document Patch Operations



API overview

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

  • Session API
  • Session API using defer
  • Operations API

Session API

  • This interface allows performing most common patch operations.

  • Multiple patch methods can be defined on the session and are sent to the server for execution in a single batch (along with any other modified documents) only when calling SaveChanges.

  • This API includes the following patching methods (see examples below):

    • patch
    • addOrPatch
    • increment
    • addOrIncrement
    • patchArray
    • addOrPatchArray

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.

Operations API

  • Operations 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

Change value of single field:


// Modify FirstName to Robert using the 'patch' method
// ===================================================

session.advanced.patch("employees/1-A", "FirstName", "Robert");        
await session.saveChanges();
// 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();
// 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);

Change values of two fields:


// 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();
// 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();
// 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);

Increment value:


// Increment UnitsInStock property value by 10
// ===========================================

session.advanced.increment("products/1-A", "UnitsInStock", 10);
await session.saveChanges();
// 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();
// 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);

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.

// 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();
class User {
    constructor(
        id = null,
        firstName = "",
        lastName = "",
        loginCount = 0,
        lastLogin = new Date(),
        loginTimes = []
    ) {
        Object.assign(this, {
            id,
            firstName,
            lastName,
            loginCount,
            lastLogin,
            loginTimes
        });
    }
}

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.

// 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();        
class User {
    constructor(
        id = null,
        firstName = "",
        lastName = "",
        loginCount = 0,
        lastLogin = new Date(),
        loginTimes = []
    ) {
        Object.assign(this, {
            id,
            firstName,
            lastName,
            loginCount,
            lastLogin,
            loginTimes
        });
    }
}

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.

// 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();
// 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();
// 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);
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
        });
    }
}

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.

// 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();
class User {
    constructor(
        id = null,
        firstName = "",
        lastName = "",
        loginCount = 0,
        lastLogin = new Date(),
        loginTimes = []
    ) {
        Object.assign(this, {
            id,
            firstName,
            lastName,
            loginCount,
            lastLogin,
            loginTimes
        });
    }
}

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.

// 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();
// 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);
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
        });
    }
}

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.

// 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();
// 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);
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
        });
    }
}

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.

// 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();
// 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);
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
        });
    }
}

Load documents in a script:


  • Loading documents is supported only by the defer or the operations syntax.

// 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();
// 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);

Remove property:


  • Removing a property is supported only by the defer or the operations syntax.

// 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();
// 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);

Rename property:


  • Renaming a property is supported only by the defer or the operations syntax.

// 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();
// 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);

Add document:


  • Adding a new document is supported only by the defer or the operations syntax.

// 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();
// 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);

Clone document:


  • Cloning a new document is supported only by the defer or the operations syntax.

// 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();
// 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);

Attachments, Counters, Time Series, and Revisions:

Attachments, counters, time series data, and revisions from the source document will Not be copied to the new document automatically.

Create/Increment counter:


// 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();
// 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();
// 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);

Learn more about Counters in this Counters Overview.

Delete counter:


// Delete counter
// ==============

session.countersFor("products/1-A").delete("Likes");
await session.saveChanges();
// 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();
// 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);

Get counter:


// Get counter value
// =================

const counters = await session.counterFor("products/1-A").get("Likes");
// 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();
// 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);

Syntax


Session API syntax

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.

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.

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.
Note how numbers are handled with the JavaScript engine in RavenDB.

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.

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.

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.

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

session.advanced.defer(...commands);
Parameter Type Description
commands object[] List of commands that will be executed on the server.
Use the PatchCommandData command for patching.

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
}

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

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

const patchOperation = new PatchOperation(id, changeVector, patch, patchIfMissing,
    skipPatchIfChangeVectorMismatch);
Constructor Type Description
id string ID of document to be patched.
changeVector string Change vector of the document to be patched.
Used to verify that the document was not changed before the patch is executed. Can be null.
patch PatchRequest Patch request to be performed on the document.
patchIfMissing PatchRequest Patch request to be performed if no document with the given ID was found. Will run only if no changeVector was passed. Can be null.
skipPatchIfChangeVectorMismatch boolean An exception is thrown if:
this param is false + changeVector has value + document with that ID and change vector was not found.

List of script methods syntax

  • This is a partial list of some javascript methods that can be used in patch scripts.
  • For a more comprehensive list, please refer to Knowledge Base: JavaScript Engine.
Method Arguments Description
load string / string[] Loads one or more documents into the context of the script by their document IDs.
loadPath A document and a path to an ID within that document Loads a related document by the path to its ID.
del Document ID; change vector; Delete the given document by its ID. If you add the expected change vector and the document's current change vector does not match, the document will not be deleted.
put Document ID; document; change vector; Create or overwrite a document with a specified ID and entity. If you try to overwrite an existing document and pass the expected change vector, the put will fail if the specified change vector does not match the document's current change vector.
cmpxchg Key Load a compare exchange value into the context of the script using its key.
getMetadata Document Returns the document's metadata.
id Document Returns the document's ID.
lastModified Document Returns the DateTime of the most recent modification made to the given document.
counter Document; counter name; Returns the value of the specified counter in the specified document.
counterRaw Document; counter name; Returns the specified counter in the specified document as a key-value pair.
incrementCounter Document; counter name; Increases the value of the counter by one.
deleteCounter Document; counter name; Deletes the counter.
timeseries Document; the time series' name; Returns the specified time series object.