如何使用查询更新Documentdb中的文档?

时间:2016-11-18 19:25:09

标签: azure-cosmosdb

如何使用查询更新Document db中的文档(基本上是想使用存储过程更新文档)?

1 个答案:

答案 0 :(得分:5)

以下示例可能是您所需要的:https://github.com/aliuy/documentdb-serverside-js/blob/master/stored-procedures/update.js

这是一个简化版本:

function updateSproc(id, update) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();
    var response = getContext().getResponse();

    tryQueryAndUpdate();

    function tryQueryAndUpdate(continuation) {
        var query = {query: "select * from root r where r.id = @id", parameters: [{name: "@id", value: id}]};
        var requestOptions = {continuation: continuation};

        var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
            if (err) throw err;

            if (documents.length > 0) {
                tryUpdate(documents[0]);
            } else {
                throw new Error("Document not found.");
            }
        });
    }

function tryUpdate(document) {
    var requestOptions = {etag: document._etag};

    var fields, i;

    fields = Object.keys(update);
    for (i = 0; i < fields.length; i++) {
       document[fields[i]] = update[fields[i]];
    }

    var isAccepted = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) {
        if (err) throw err;
        response.setBody(updatedDocument);
    });
}