如何使用查询更新Documentdb中的文档? [英] How to update a document in Documentdb using queries?

查看:61
本文介绍了如何使用查询更新Documentdb中的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

以下示例可能是您需要的:

How to update a document in Document db using queries ( basically want to update a document using a stored procedure)?

The following sample might be what you need: https://github.com/aliuy/documentdb-serverside-js/blob/master/stored-procedures/update.js.

Here's a simplified version:

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);
    });
}

这篇关于如何使用查询更新Documentdb中的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆