如何在PouchDb中更新复杂文档的部分更新或其他方法?

时间:2014-08-10 15:46:22

标签: javascript json join pouchdb nosql

我有一个像这样的复杂文档:

    {
   "_id": "07394B10-DEB7-E703-BB97-37B694FA0877",
   "_rev": "2-9a2c5809802024a8d35cc9fbba9ea885",
   "name": "Ivrea",
   "number": "1",
   "owners": [
       {
           "name": "Ale",
           "address": "Via Ale 2",
           "gender": "Uomo",
           "type": "Assente",
           "date": "2014-08-10",
           "notes": [
               {
                   "text": "Foo",
                   "date": "2014-08-10"
               }
           ]
       }
   ]
}

如何部分更新?防爆。只有owners.name或者owner.notes.date? 如果我要做一个"加入"使用链接文档方法,如何使用此示例拆分所有者和注释? 谢谢你的回答!

1 个答案:

答案 0 :(得分:1)

连接确实似乎是你最好的选择,因为PouchDB中没有办法只更新文档的“部分” - 你必须更新整个文件。

这样的事情怎么样?假设你有车主和车。

var owner = {
  _id: 'owner_1', // could be 'owner_' + Math.random() or whatever
  name: 'Cookie Monster',
  type: 'owner'
};

var car = {
  _id: 'car_1', // ditto
  name: 'Mach 5',
  type: 'car',
  ownerId: 'owner_1' // Cookie Monster drives the Mach 5 :)
};

var db = new PouchDB('mydb');

db.bulkDocs([owner, car]).then(function () {
  return db.put({
    _id: '_design/owners_and_cars',
    views: {
      owners_and_cars: {
        map: function (doc) {
          if (doc.type === 'car') {
            emit(doc._id, {_id: doc.ownerId});
          }
        }.toString()
      }
    }
  }).catch(function (err) {
    if (err.status !== 409) {
      // 409 means already exists
      throw err;
    }
  });
}).then(function () {
  return db.query('owners_and_cars', {include_docs: true});
}).then(function (res) {
  console.log(JSON.stringify(res));
}).catch(function (err) { 
  /* ... */
});

打印:

{
  "total_rows": 1,
  "offset": 0,
  "rows": [
    {
      "id": "car_1",
      "key": "car_1",
      "value": {
        "_id": "owner_1"
      },
      "doc": {
        "name": "Cookie Monster",
        "type": "owner",
        "_id": "owner_1",
        "_rev": "1-f702c1d279add84b30c6464070d8a985"
      }
    }
  ]
}

如果您有大量数据,这可能会很慢,因为二级索引很慢。在这种情况下,您可以显式执行allDocs查询:

db.allDocs({startkey: 'car_', endkey: 'car_\uffff'}); // finds all cars
db.allDocs({startkey: 'owner_', endkey: 'owner_\uffff'}); // finds all owners

然后你会手动进行连接。