Question

Let's say that you have the following doc:

{ title: 'take out the trash', priority: 'medium' }

and you have two different clients editing this data simultaneously, e.g. client 1 wants to change the title to clean the dishes and client 2 wants to change the priority to high.

How can this be implemented using pouchdb?

Was it helpful?

Solution

Update handlers and partial updates are supported in couchdb, but they require a REST call for each update, which defeats the purpose of using pouchdb to work offline and sync later. Another solution is to use the every doc is a delta method.

This function retrieves all the docs:

function merge(obj1, obj2) {
  for (var i in obj2) {
    obj1[i] = obj2[i];
  }
}

function all(db) {
  return new Promise(function(fulfill, reject) {
    var docs = {};
    db.allDocs({include_docs: true}, function(err, doc) {

      // sort by createdAt as cannot guarantee that order preserved by pouch/couch
      doc.rows.sort(function(a, b) {
        return a.doc.$createdAt > b.doc.$createdAt;
      });

      doc.rows.forEach(function(el, i) {
        if (!el.doc.$id) { // first delta for doc?
          el.doc.$id = el.doc._id;
        }
        if (docs[el.doc.$id]) { // exists?
          merge(docs[el.doc.$id], el.doc);
        } else {
          docs[el.doc.$id] = el.doc;
        }
        if (i == doc.rows.length - 1) { // last element?
          fulfill(docs);
        }
      });
    });
  });
}

and this function allows you to make partial updates:

function put(object, db) {
  object.$createdAt = (new Date()).toJSON();
  return new Promise(function(fulfill, reject) {
    db.post(object).then(function(object) {
      fulfill(object);
    });
  });
}

For a complete example, see Partial Updates Using Pouch

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top