Ad

How To Use DocumentDB's Pre-Trigger On Insert Operation To Approve/disapprove The Insertion

- 1 answer

I need to create a condition when insert into DocumentDB table. I'm using .NET SDK.

When I use the insert operation I would like to compare the document to the rest of the documents and approve the insertion only if there is no other document containing the same value in a specific field.

Other option is to define a column as unique, only that in my case it is two columns that should be unique.

Here the trigger I made, for some reason it is not preventing the INSERT operation.

the fields to compare are "ApplicationSession" and "OperationCounter"

function UniqueAppSessionAndCounter() {
var collection = getContext().getCollection();
var request = getContext().getRequest();
var docToCreate = request.getBody();


if (!docToCreate.ApplicationSession || docToCreate.ApplicationSession == ""
    || !docToCreate.OperationCounter || docToCreate.OperationCounter == 0) {
    throw new Error('Application session and Counter is a must');
}


var filterQuery = 'SELECT * FROM r WHERE r.ApplicationSession = "'
                      + docToCreate.ApplicationSession + '" AND r.OperationCounter = '
                      + docToCreate.OperationCounter;
collection.queryDocuments(collection.getSelfLink(), filterQuery
   , function (err, docs, options) {
       if (docs.length > 0) {
           throw new Error('Application session and Counter must be unique');
       }
   });}
Ad

Answer

Are you sure that you are executing the Trigger when you call CreateDocumentAsync?

In DocumentDB, trigger execution is not automatic like you might expect. This is because you often have different documents going in to a single collection and you might want different triggers for different types of documents.

To execute the document when creating the document make sure you specify to include the trigger as follows:

CreateDocumentAsync(coll_link, 
    new {foo: "bar"}, 
    new RequestOptions {IncludePreTrigger = "TriggerName"}); 
Ad
source: stackoverflow.com
Ad