【问题标题】:Add new property to a document in DocumentDB with nodejs使用 nodejs 向 DocumentDB 中的文档添加新属性
【发布时间】:2017-11-02 19:54:40
【问题描述】:

我在 DocumentDB 中有一个 JSON 文档。

我希望向给定文档添加新数据。

例如。

当前文档:

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

新建文档

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

我已经尝试过这里提到的解决方案:

Add new properties to DocumentDB Document in Stored procedure

但我得到“getContext is not defined”。

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

我想要:

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”而不是文档本身。

提前感谢您的帮助!

【问题讨论】:

  • 您需要将存储过程实际上传到 Cosmos 并在那里调用它。 getContext 特定于该运行时环境,您不能只在随机节点脚本中运行它
  • 我明白了,有没有不用存储过程编辑文档的方法?
  • 否,除非您使用存储过程,否则您只能创建、更新插入或替换整个文档。您将无法修改个别属性

标签: node.js azure azure-cosmosdb


【解决方案1】:

是的,您需要改用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');
    });
});

【讨论】:

  • 太棒了,非常感谢!在属性列表中的哪个位置排序是否容易?
  • 你应该在调用replaceDocument方法之前以编程方式订购属性。
  • 嗨,很抱歉,这对您来说是什么意思?设置 doc.currentProperty1 = "";, doc.currentProperty2 = "";像那样?
  • 或者更好的是,我不能在 doc.abc1 之后指定 'doc.abc = "123"' - 原因是我有多个脚本要添加到文档中 - 这样做当前方法我需要为每个脚本指定一个严格的顺序来添加文档。
  • 现在您的问题是关于在 Javascript 中对对象的属性进行排序。它与 DocumentDB SDK 无关。
猜你喜欢
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2011-09-05
  • 2013-01-15
  • 2015-10-10
  • 1970-01-01
相关资源
最近更新 更多