首页 > 解决方案 > 插入新文档时未运行 Cosmos Db 触发器

问题描述

我正在使用 Azure Cosmos DB。我在 Azure Portal 中创建了一个简单的触发器,如下所示:

在此处输入图像描述

  var context = getContext();
  var request = context.getRequest();

  // item to be created in the current operation
  var itemToCreate = request.getBody();
  itemToCreate["address"] = "test";

  // update the item that will be created
  request.setBody(itemToCreate);

不幸的是,当我插入新文档时,没有触发这个触发器。我还尝试将“触发类型”设置为“发布”。我错过了什么吗?

标签: javaazureazure-cosmosdbazureportalazure-java-sdk

解决方案


好问题!我一直认为触发器会自动运行:)。

我相信只要插入文档,触发器就不会自动运行。您需要做的是指定在创建文档时要运行的触发器。

您需要做的是在发送创建文档请求时通过将触发器名称作为请求选项传递来注册触发器。

例如,请参阅此处的代码:https ://docs.microsoft.com/en-us/azure/cosmos-db/how-to-use-stored-procedures-triggers-udfs#pre-triggers (也复制如下)。注意PreTriggerIncludein的使用RequestOptions

dynamic newItem = new
{
    category = "Personal",
    name = "Groceries",
    description = "Pick up strawberries",
    isComplete = false
};

Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
RequestOptions requestOptions = new RequestOptions { PreTriggerInclude = new List<string> { "trgPreValidateToDoItemTimestamp" } };
await client.CreateDocumentAsync(containerUri, newItem, requestOptions);

推荐阅读