2
votes

I'm trying to write little pre-insert trigger ( to generate numeric ids for each document in collection ), register it and run using DocumentDB .NET SDK. I'm using DocumentDB emulator to test my code

function generateNumericId() {
var counterDocumentId = 'numericIdCounter';
var counterDocumentLink = __.getSelfLink() + 'docs/' + counterDocumentId;
__.readDocument(counterDocumentLink, {},
    function(err, counterDocument) {
        if (err) throw new Error("Can't find counterDocument!");
        counterDocument.value += 1;
        __.upsertDocument(counterDocumentLink, counterDocument);
        var docToCreate = __.request.getBody();
        docToCreate.id = counterDocument.value.toString();
        __.request.setBody(docToCreate);
    });}

My .net code registers it sucessfully but when i'm running insert operation it fails with "Error creating request message" exception. So, please, tell me what is wrong with my code? (!IMPORTANT : I already have numericIdCounter document inside the collection, js code fails at readDocument function!)

1
js code fails at readDocument function Please try to log error details to a field of docToCreate and check if could find useful info from error. - Fei Han
but __.readDocument don't even runs the callback, so how can i log a details inside of it? - Алексей Ковалевский

1 Answers

3
votes

The 1st mistake : __.getSelfLink() => __.getAltLink() because getSelfLink() provides path built from internal _id fields (it's not ok for us - we know only counter id, not internal _id). getAltLink() allows us to build urls like the following : dbs/mydb/colls/mycoll/docs/numericIdCounter instead of dbs/dLIxAA==/colls/dLIxAOFiYAA=/docs/dLIxAOFiYAABAAAAAAAAAA==/.

The 2nd mistake : __.upsertDocument(counterDocumentLink, counterDocument); => __.upsertDocument(__.getAltLink(), counterDocument); just after checking api documentation.