4

I have created a simple Pre Trigger in my CosmosDB collection.

function testTrigger() {
    var context = getContext();
    var request = context.getRequest();
    var documentToCreate = request.getBody();
    documentToCreate["test"] = "Added by trigger";
    request.setBody(documentToCreate);
}

Though it seems, this trigger isn't fired at all.

What's also irritating, the getContext() call is marked with a green squiggly line in the script explorer.

enter image description here

Larry Maccherone
  • 9,393
  • 3
  • 27
  • 43
Thomas Mutzl
  • 715
  • 7
  • 21

1 Answers1

17

The problem that the trigger doesn't seem to be... well... triggered, is that you aren't specifying it on the triggering operation. Triggers are not automatic. They must be specified for each database operation where you want them executed.

Personally, I think that was a unfortunate design choice and I've decided to not use triggers at all in my own code. Rather, I embed all the business rule constraints in stored procedures. I find this to be a bit cleaner and removes the worry that I'll forget to specify a trigger or (more likely) someone else writing code to the database won't even know that they should. I realize that someone can bypass my stored procedure and violate the business rules by going directly to the documents, but I don't know of any way in DocumentDB to protect against that. If there was a way to make triggers be automatic, that would have protected against that.

When using the REST API, you specify triggers in a header with x-ms-documentdb-pre-trigger-include or x-ms-documentdb-post-trigger-include. In the node.js SDK, you use the RequestOptions preTriggerInclude or preTriggerInclude property. For .NET, you specify it like this:

Document createdItem = await client.CreateDocumentAsync(collection.SelfLink, new Document { Id = "documentdb" },
new RequestOptions
{
    PreTriggerInclude = new List<string> { "CapitalizeName" },
});

See comments for discussion on the green squiggly.

Larry Maccherone
  • 9,393
  • 3
  • 27
  • 43
  • 3
    Wow! That's not intuitive. I wouldn't expect, that I have to explicitly specify triggers I want to be executed on an operation. Tanks for this answer! – Thomas Mutzl Sep 20 '15 at 18:44
  • Interestingly, the __ is also underlined with a green squiggly. But thanks for pointing that out - I didn't know about this shortcut. – Thomas Mutzl Sep 20 '15 at 18:45
  • OK, so I'm only batting 500 on my "best guesses". :-) My second best guess on the green squiggly is that the identifier is not declared within the sproc. My IDE does this when accessing global JavaScript identifiers. – Larry Maccherone Sep 21 '15 at 00:48
  • 2
    Yes, as I said, not making triggers automatic is an unfortunate design decision, IMHO. – Larry Maccherone Sep 21 '15 at 00:49
  • Removing the green squiggly aspect of my answer and making this a wiki answer. – Larry Maccherone Sep 21 '15 at 13:47