Skip to content

Instantly share code, notes, and snippets.

@roydejong
Last active July 4, 2017 14:02
Show Gist options
  • Save roydejong/47356ed12f2676737cdf968614578922 to your computer and use it in GitHub Desktop.
Save roydejong/47356ed12f2676737cdf968614578922 to your computer and use it in GitHub Desktop.
PouchDB: Add or update record (sync / merge)
static addOrUpdate(id, document) {
return new Promise(function (resolve, reject) {
let doStore = function (originalDocument) {
// Merge the document: First, set the ID. Then apply the existing doc on top if possible. Finally, apply the changed doc.
let mergedDoc = {
_id: id
};
if (originalDocument) {
for (let key in originalDocument) {
mergedDoc[key] = originalDocument[key];
}
}
for (let key in newDocument) {
mergedDoc[key] = newDocument[key];
}
// Verify whether the merged document actually has any changed properties other than revision
if (originalDocument) {
let anyUnequal = false;
for (let key in mergedDoc) {
if (key === "_rev") {
continue;
}
if (originalDocument[key] !== mergedDoc[key]) {
console.log('PROP NOT EQUAL', key);
anyUnequal = true;
break;
}
}
if (!anyUnequal) {
// All properties equal, no need to perform merge
resolve(mergedDoc);
return;
}
}
// Update needed, perform put
DeviceDb.db.put(mergedDoc).then(function (response) {
mergedDoc._rev = response.rev;
resolve(mergedDoc);
})
.catch(function (err) {
reject(err);
});
};
// Fetch the document, see what happens, then store or update
db.get(id).then(function (getDoc) {
// Document exists, update
doStore(getDoc);
}).catch(function (err) {
if (err.status === 404) {
// Document does not exist, create
doStore(null);
} else {
// Something else went wrong, general failure
reject(err);
}
});
});
}
@roydejong
Copy link
Author

roydejong commented Jul 4, 2017

Example use:

ExDbClass.addOrUpdate("mydoc", { description: "changed" }).then(function (document) {
    console.log(document); // Object {_id: "mydoc", description: "new", _rev: "1-4d4874e4817ded18aa5575d74f0f1c52"}
});

And again:

ExDbClass.addOrUpdate("mydoc", { secondary: "update" }).then(function (document) {
    console.log(document); // Object {_id: "mydoc", description: "new", _rev: "2-803b42574d364351252a7564edd3f564", secondary: "update"}
});

Also, it won't create a new revision if nothing changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment