6

I create a pouchDB document with "_id", "name", and "status" fields. However, I find that if I want to update the "status" field of the document then I need to also specify all the other fields I am NOT changing as well otherwise they get erased. That is, if I do not specify the "name" field on update, there will no longer be a "name" field on the document.

function createFriendSchedule(friend){

  pouchDB.put({

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

  }, function(err, response){

    createAndDispatchEvent("friend Schedule created");

  });


}

This is the code for updating the document

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

    });


  });

}

And here is the code used to pull the record out

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

    });

If I don't specify the "name" field on update, the array returned by the emit() call in pouchDB.query contains a null value where I expect the "name" value to be.

4

1 回答 1

12

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

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

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

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

于 2014-05-12T18:44:50.793 回答