如何更新pouchDB文档中的单个字段

Joe*_*eyC 3 javascript pouchdb

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

function createFriendSchedule(friend){

  pouchDB.put({

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

  }, function(err, response){

    createAndDispatchEvent("friend Schedule created");

  });


}
Run Code Online (Sandbox Code Playgroud)

这是更新文档的代码

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

    });


  });

}
Run Code Online (Sandbox Code Playgroud)

这是用于拉出记录的代码

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

    });
Run Code Online (Sandbox Code Playgroud)

如果我没有在update上指定"name"字段,pouchDB.query中的emit()调用返回的数组包含一个空值,我期望"name"值.

nla*_*son 9

CouchDB和PouchDB的设计使得文档是原子的.实际上,如果要更新单个字段,则必须put()使用整个文档.

在您的示例中使这更容易的一种方法是retreived直接使用该值,而不是创建新对象并手动复制字段.您还可以将文档拆分为多个类型的小文档,而不是一个必须不断读取和重写的单个大文档.

您可能还想考虑使用allDocs而不是query,因为如果您只需要通过ID获取文档,它通常会更快.该PouchDB博客对分页和索引可帮助这里的几篇文章.

编辑:现在有一个pouchdb-upsert插件,可以更容易地更新单个字段.在引擎盖下,它只是做了一个put().