cosmos-db
  1. cosmos-db-triggers

Triggers in CosmosDB with .NET

Syntax

Triggers in CosmosDB with .NET can be defined in JavaScript and are executed before or after an insert, update or delete operation on a document. The syntax to define a trigger is as follows:

function triggerFunction() {
  // Trigger function body
}

Example

Let's take an example of a CosmosDB container where we want to maintain a revision history of the documents whenever they are updated. We can define a trigger function that will create a new document in the revision history container for every update operation.

function updateRevisionHistory() {
    var context = getContext();
    var collection = context.getCollection();
    var response = context.getResponse();
    var documentToCreate = context.getRequest().getBody();    
    documentToCreate._id = documentToCreate._self + "_" + new Date().getTime();
    collection.createDocument("dbs/revisionHistory/colls/myRevisionHistory", documentToCreate, {},
        function(err, documentCreated) {
            if (err) throw new Error("Error: " + err.message);
            response.setBody(documentCreated);
        });
}

Explanation

In the above example, the trigger function updateRevisionHistory is defined which will create a new document in the myRevisionHistory collection for every update operation.

Here's an explanation of the code:

  • getContext() and getResponse() functions are used to get the current context and the response object respectively.
  • getCollection() function is used to get the current collection object.
  • getRequest().getBody(); is used to get the updated document.
  • _id property is set as ${_self}_${timestamp} which will create a unique ID for the document.
  • collection.createDocument() function is used to create a new document in the revision history collection.

Use

Triggers in CosmosDB with .NET can be used to perform various tasks like:

  • Maintaining a revision history of documents.
  • Validating the incoming data.
  • Performing complex calculations.

Important Points

  • Triggers can be defined for a container in CosmosDB.
  • Triggers can only be defined in JavaScript.
  • Triggers can be executed before or after the operation.

Summary

Triggers in CosmosDB with .NET can be defined in JavaScript and are executed before or after an insert, update or delete operation on a document. They can be used to perform various tasks like maintaining a revision history of documents, validating incoming data and performing complex calculations.

Published on: