0
votes

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.

1

1 Answers

0
votes

You shouldn't try to do the write in your trigger. You should simply modify the body or throw an error. In modifying the body, you change the document that is created. In throwing an error you abort the operation.

So instead of:

var isAccepted = collection.createDocument(collection.getSelfLink(), docToCreate);

Do:

return request.setBody(docToCreate);