Skip to content

Instantly share code, notes, and snippets.

@7ictor
Last active April 26, 2018 10:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 7ictor/83a9580cddd408f983a7 to your computer and use it in GitHub Desktop.
Save 7ictor/83a9580cddd408f983a7 to your computer and use it in GitHub Desktop.
CouchDB update handler for partial updates of a document.
function (doc, req) {
var findTheChanges = function (prevK, obj) {
var arr = [];
for (var key in obj) {
var prevKey = prevK || '';
if (obj.hasOwnProperty(key)) {
var value = obj[key];
// If its an Object dig deeper.
if (value !== null &&
typeof value === 'object' &&
value.constructor !== Array) {
prevKey += key;
prevKey += ',';
var deepArr = findTheChanges(prevKey, value);
arr = arr.concat(deepArr);
}
// Found the value to affect.
else {
arr.push({
path: prevKey + key,
value: value
});
}
}
}
return arr;
};
if (!doc) {
return [null, JSON.stringify({
doc: req.id,
status: 'nodoc'
})];
}
var _obj = JSON.parse(req.body);
var arrayOfChanges = findTheChanges(null, _obj);
for (var i = 0, len1 = arrayOfChanges.length; i < len1; i++) {
var path = (arrayOfChanges[i].path).split(',');
var value = arrayOfChanges[i].value;
var newDoc = doc;
for (var j = 0, len2 = path.length; j < len2; j++) {
// If it's not the final value, and niether is an Object,
// it should be an empty Object to build the new chain.
if (j + 1 < len2 &&
(typeof newDoc[path[j]] !== 'object' ||
newDoc[path[j]].constructor === Array ||
newDoc[path[j]] === null)) {
newDoc[path[j]] = {};
}
if (j + 1 === len2) newDoc[path[j]] = value;
else newDoc = newDoc[path[j]];
}
}
return [doc, JSON.stringify({
doc: req.id,
status: 'updated'
})];
}
@brhrmaster
Copy link

Could you please fix this: instead of return newDoc object the database needs to receive the modified DOC object.

return [ doc, JSON.stringify({ status: 'updated' }) ];

@7ictor
Copy link
Author

7ictor commented Aug 17, 2016

Thanks @brhrmaster, I forgot to update after publish and test 😄

@Ayyappan-RK
Copy link

How do i use this partial-update.js in my pouch code

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