使用nodejs将新属性添加到DocumentDB中的文档

时间:2017-11-02 19:54:40

标签: node.js azure azure-cosmosdb

我在DocumentDB中有一个JSON文档。

我希望将新数据添加到给定文档中。

例如。

当前文件:

{
    "User": "ABC",
    "UserID": "123"
}

新文件

{
    "User": "ABC",
    "Height":"1.60",
    "UserID": "123"
}

我尝试过如下所述的解决方案:

Add new properties to DocumentDB Document in Stored procedure

但我得到" getContext未定义"。

我认为问题在于我不确定如何通过函数调用文档。

我想:

var documentURL = "dbs/'dbname'/colls/'collsname'/docs/'docsname'"
editDocument(documentURL)

function editDocument(document) {
    var collection = getContext().getCollection();
    var response = getContext().getResponse();

    document.Height = "1.60";

    collection.createDocument(collection.getSelfLink(), document, function(err, result) {
    if(err) throw err;

       // Return the resulting document back as the response.
       response.setBody(result);
    });
}

我应该使用client.replaceDocument,或者可能有更好的方法来执行此操作。

问题可能是该功能明显试图使用文本位置" dbs / colls / docs"在函数而不是文档本身。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

是的,您需要改为使用replaceDocument

var documentURL = "dbs/'dbname'/colls/'collsname'/docs/'docid'"

client.readDocument(documentURL, (err, doc) => {
    if(err) return console.log(err);

    doc.Height = "1.60";

    client.replaceDocument(documentUrl, doc, (err, result) => {
        if(err) return console.log(err);
        console.log('replaced document');
    });
});
相关问题