【问题标题】:How to add new fields to document in Cloudant without losing existing ones如何在 Cloudant 中向文档添加新字段而不丢失现有字段
【发布时间】:2017-07-07 19:46:13
【问题描述】:

我正在尝试根据用户输入向 Cloudant 中的文档添加新字段,但是当我执行插入操作时,我会覆盖文档并丢失现有字段,除非我使用 insert 发送它们。

例如,我有一个命令对 Cloudant 执行查询以接收文档,并返回 _id, _rev, name and special_id 字段。该文档通过插入传递给一个新命令,该命令附加一个字段,例如favorite_food(是的,我正在使用_rev)。

现在,用户输入另一个命令,例如“添加学校”。该过程重新开始,我查询 Cloudant,我的查询返回了 _id, _rev, name, and special_id。我在文档中附加了一个school 字段,然后执行了一个insert,但随后我检查了文档,favorite_food 消失了。

是否有一个参数可以传递给 Cloudant insert 函数来告诉它实际执行更新而不是覆盖?

仅供参考,这是在 Node 上运行并使用 node-cloudant 包。在文档中我找不到有关参数的更多详细信息,典型的插入看起来像:

cloudantDb.insert(doc, params, function(error, response) {
  if (!error) {
    console.log("success", response);
    resolve(response);
  } else {
    console.log("error", error);
    reject(error);
  }
});

【问题讨论】:

    标签: javascript node.js cloudant


    【解决方案1】:

    没有看到您的代码,很难确定。没有神奇的参数。在 Cloudant 中,创建、更新和删除之间没有区别——它们本质上都是在创建修订。您不能“修补” JSON 文档,您需要每次都提供整个内容。这是一个例子:

    # Create a new document
    curl -XPOST -H 'content-type:application/json' \
        'https://skruger.cloudant.com/testdb' -d '{"name":"stefan"}'
    {"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"1-a0f0b27e1069f45cc121dfe5dc08f280"}
    
    # Add a field
    curl -XPUT -H 'content-type:application/json' \
     'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' \
      -d '{"_id":"5309a1784a9cc45d498e8170af7dcc3c", "_rev":"1-a0f0b27e1069f45cc121dfe5dc08f280", "name":"stefan", "fish":"pike pearch"}'
    {"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"2-7c3ea3603c3e16962c7b33f50becc771"}
    
    # Fetch it again
    curl 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' 
    {"_id":"5309a1784a9cc45d498e8170af7dcc3c","_rev":"2-7c3ea3603c3e16962c7b33f50becc771","name":"stefan","fish":"pike pearch"}
    
    # And another new field
    curl -XPUT -H 'content-type:application/json' \
     'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' \
     -d '{"_id":"5309a1784a9cc45d498e8170af7dcc3c", "_rev":"2-7c3ea3603c3e16962c7b33f50becc771", "name":"stefan", "fish":"pike pearch", "sport":"tennis"}'
     {"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"3-e0f4d1ab1a47b046ea90a0fbbf34ff36"}
    
    # Fetch again    
    curl 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c'
    {"_id":"5309a1784a9cc45d498e8170af7dcc3c","_rev":"3-e0f4d1ab1a47b046ea90a0fbbf34ff36","name":"stefan","fish":"pike pearch","sport":"tennis"}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 2012-10-27
      • 2013-06-24
      • 1970-01-01
      相关资源
      最近更新 更多