【问题标题】:How to update a single field in a pouchDB document如何更新 pouchDB 文档中的单个字段
【发布时间】:2014-06-29 15:21:28
【问题描述】:

我创建了一个带有“_id”、“name”和“status”字段的 pouchDB 文档。但是,我发现如果我想更新文档的“状态”字段,那么我还需要指定我没有更改的所有其他字段,否则它们会被删除。也就是说,如果我在更新时不指定“名称”字段,则文档上将不再有“名称”字段。

function createFriendSchedule(friend){

  pouchDB.put({

    _id : friend['id'],
    name : friend['name'],
    status: "new"

  }, function(err, response){

    createAndDispatchEvent("friend Schedule created");

  });


}

这是更新文档的代码

function changeFriendStatus(friend){

  pouchDB.get(friend['id'], function(err, retrieved){

    pouchDB.put({

      _id : friend['id'],
      _rev : retrieved._rev, //need to specify _rev otherwise conflict will occur
      name : retrieved.name, //if you don't specify name should remain the samme as before, then it will be left off the record!
      status : friend['status']

    }, function(err, response){

      if(err){  

    console.log("COULDN'T CHANGE FRIEND STATUS");

      } else {  createAndDispatchEvent("friend status changed") }

    });


  });

}

这是用于提取记录的代码

  window.pouchDB.query(
    {map : map}, 
    {reduce : false}, 
    function(err, response){

      var responseRows = response['rows'];
      var cleanedList = [];
      _.each(responseRows, function(friend){    

    cleanedList.push({'_id' : friend['key'][0], 'name' : friend['key'][1], 'status' : friend['key'][2] });

      });
      window.reminderList = cleanedList;
      console.log(window.reminderList);
      createAndDispatchEvent("Returned reminder list");

    });

如果我没有在更新时指定“名称”字段,则 pouchDB.query 中的 emit() 调用返回的数组包含一个空值,我希望“名称”值是这个值。

【问题讨论】:

    标签: javascript pouchdb


    【解决方案1】:

    CouchDB 和 PouchDB 的设计方式是文档是原子的。所以确实,如果你想更新单个字段,你必须put()整个文档。

    在您的示例中简化此操作的一种方法是直接使用 retreived 值,而不是创建新对象并手动复制字段。您还可以将文档拆分为许多具有多种类型的小文档,而不是一个必须不断阅读和重写的大文档。

    您可能还想考虑使用allDocs 而不是query,因为如果您只需要按ID 获取文档,它通常会更快。 PouchDB blog 有几篇关于分页和索引的文章,在这里可能会有所帮助。

    编辑:现在有一个pouchdb-upsert 插件可以更轻松地更新单个字段。在引擎盖下,它只是执行put()

    【讨论】:

    • 感谢您创建了如此出色的库 :) 我真的认为现在可以在浏览器中完成的所有事情都是理所当然的!对于希望能够更新单个(或多个)字段而无需显式更新所有其他字段的任何人,我在下面发布了一个可能的解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2017-06-03
    • 2020-11-28
    • 2015-04-12
    • 2020-10-23
    相关资源
    最近更新 更多