【发布时间】:2016-05-12 16:28:09
【问题描述】:
我正在尝试在 Azure DocumentDb 集合上实现触发器,该触发器应该自动增加正在插入的文档版本。触发器被创建为预触发器。
我面临的挑战是集合类似乎没有提供用于查询数据的同步 API。我的触发器计划是查询现有文档,获取最高版本,递增,并将 +1 值分配给正在插入集合中的文档。但由于查询的结果只能异步获得,到那时我的触发器已完成,文档未修改地插入。
如何等待查询结果?
这是我当前触发器的样子:
// TRIGGER Auto increment version
function autoIncrementVersion() {
var collection = getContext().getCollection();
var request = getContext().getRequest();
var docToCreate = request.getBody();
// Reject documents that do not have a name property by throwing an exception.
if (!docToCreate.Version) {
throw new Error('Document must include a "Version" property.');
}
var lastVersion;
var filter = "SELECT TOP 1 d.Version FROM CovenantsDocuments d ORDER BY d.Version DESC";
var result = collection.queryDocuments(collection.getSelfLink(), filter, {},
function (err, documents, responseOptions) {
if (err) throw new Error("Error: " + err.message);
if (documents.length != 1 || !documents[0]) {
lastVersion = 0;
} else {
lastVersion = documents[0];
}
//By the time we reach this line, our trigger has already completed?
docToCreate.Version = lastVersion + 1;
});
if (!result) throw "Unable to read last version of the document";
}
更新:问题在于我提交请求的方式。看起来默认情况下不会触发触发器,它们的名称需要作为请求的参数显式提供。 在我的情况下,直到我将客户端代码更改为此触发器才触发:
RequestOptions options = new RequestOptions
{
PreTriggerInclude = new[] { "autoIncrementVersion"}
};
client.CreateDocumentAsync(url, document, options);
【问题讨论】:
标签: javascript azure azure-cosmosdb