Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update another collection in an Azure Document DB stored procedure

We need to update the all the documents in a collection to change their shape. We'd like to record an audit of the change in a different collection where we will store a document which contains the old and new version. In order to make this change atomic, we are using a stored proc.

The issue we are facing is updating another collection from a stored proc. It seems the audit document is always written into the collection the stored proc belongs to.

I have written up a sample stored proc:

function sample(prefix) {
    var context = getContext();
    var fooCollection = context.getCollection();
    var barCollection = context.getCollection("BarCollection");

    // Query documents and take 1st item.
    var isAccepted = fooCollection.queryDocuments(
        fooCollection.getSelfLink(),
        'SELECT * FROM root r',
        function (err, feed, options) {
            if (err) throw err;

            // Check the feed and if empty, set the body to 'no docs found', 
            // else take 1st element from feed
            if (!feed || !feed.length) context.getResponse().setBody('no docs found');
            else {
                var fooDoc = feed[0];

                var barDoc = {
                    "foo" : fooDoc,
                    "bar" : "bar"
                }

                var isAccepted2 = barCollection.createDocument(barCollection.getSelfLink(), barDoc);  

                if (!isAccepted2) throw new Error('The query was not accepted by the server.'); 
            } 

        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

In this sample, my stored proc is saved in the FooCollection. I get a document and try to save a copy into the BarCollection. The new document is always saved into the FooCollection.

Is this scenario supported in Document DB? If so, what changes do I need to make the stored proc to make it work?

like image 792
Kevin Kuszyk Avatar asked Jun 08 '26 02:06

Kevin Kuszyk


1 Answers

DocumentDB stored procedures are collection-scoped. You will not be able to write audit info to a separate collection; you'd need to write to the same collection.

like image 168
David Makogon Avatar answered Jun 10 '26 16:06

David Makogon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!