In DocumentDB I've create a pre trigger on Create operation. The trigger code is the following
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.");
}
The trigger is executed up to the line immediately above the var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate);.
When the var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate); is executed, this error is thrown Message: {"Errors":["Resource with specified id or name already exists"]}
I've checked and no documents with the same id of the new document is stored into this collection.