2

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!)

2
  • 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. Commented Apr 21, 2017 at 10:27
  • but __.readDocument don't even runs the callback, so how can i log a details inside of it? Commented Apr 21, 2017 at 12:18

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! Solved my problem. Unfortunately there is hardly any documentation or examples around this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.