在DocumentDB中,我在Create操作上创建了一个预触发器。触发器代码如下
function createBlock() {
var collection = getContext().getCollection();
var request = getContext().getRequest();
var docToCreate = request.getBody();
if (docToCreate.DocumentType)
{
var query = "SELECT TOP 1 a.BlockSequence FROM a ORDER BY a.BlockSequence DESC";
var isAccepted = collection.queryDocuments(collection.getSelfLink(), query, function (err, feed, options) {
if (err)
throw err;
if (!feed)
throw new Error("Failed to find the document.");
if (feed.length)
{
docToCreate.BlockCode += (feed[0].BlockSequence + 1);
docToCreate.BlockSequence = feed[0].BlockSequence + 1;
}
else
{
docToCreate.BlockCode += "1";
docToCreate.BlockSequence = 1;
}
var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate);
if (!isAccepted)
throw new Error("The call createDocument returned false.");
});
}
else
throw new Error("DocumentType property is required.");
if (!isAccepted)
throw new Error("The call queryDocuments returned false.");
}
触发器执行到var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate);
正上方的行。
执行var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate);
时,会抛出此错误Message: {"Errors":["Resource with specified id or name already exists"]}
我已经检查过,并且没有与新文档具有相同ID的文档存储在此集合中。
答案 0 :(得分:0)
您不应该尝试在触发器中执行写操作。您应该只是修改正文或抛出错误。在修改正文时,您可以更改创建的文档。在抛出错误时,您将中止操作。
所以而不是:
var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate);
执行:
return request.setBody(docToCreate);