Reputation: 4575
I am trying to loop through the fields in a CouchDB document and check that the old version of the field and new version are the same (as part of my validate_doc_update). However, I would like to do the equivalent of a "foreach field in documents, check to make sure they are the same", instead of having to say something like
oldrev.document.field1 == newrev.document.field1, oldrev.document.field2 == newrev.document.field2,
blah blah. Is there a way to do this with CouchDB fields, or do I have to specify the name of each field? It would be nice to not type them all in, and if we ever change the field names, to not have to come back in and tweak things.
Upvotes: 1
Views: 1335
Reputation: 3901
The values passed as newDoc
, and oldDoc
parameters to validate_doc_update
function are Javascript objects: you compare two documents as you compare any JS objects. There no "CouchDB field".
You can write custom code, or you can use a JS library like Underscore.js. You can include it as a CommonJS module. The only problem is the _rev
field. My approach is to keep CouchDB metadata separate from document data, by putting the data in a data
field. For example:
{ "_id": "ID", "_rev": "REV", "foo": "bar", "baz": [1, 2] }
becomes
{ "_id": "ID", "_rev": "REV", "data": { "foo": "bar", "baz": [1, 2] } }
Then the comparison can be done with
function(newDoc, oldDoc) {
var _ = require("underscore");
if (!_.isEqual(newDoc.data, oldDoc.data)) {
// something changed...
}
}
Upvotes: 1
Reputation: 28429
A JS for in
loop should suffice:
for (var key in newrev) {
if (newrev.hasOwnProperty(key) {
if (oldrev[key] === newrev[key]) {
// they are the same
}
}
}
There is one thing you'll need to be cautious of here, and that is that deleting/adding fields between revisions may be harder to validate.
I'm pretty sure Object.keys
is available to SpiderMonkey, so you may need to use that to compare the number of keys between old and new.
Upvotes: 1