Accessing the original field in Parse.com Cloud Code beforeSave
The end goal is to detect changes between an existing Parse object and an incoming update using a function beforeSave
in the cloud code.
From the cloud code log, available through parse.com, you can see that the entry in beforeSave
contains a field called original
and the other contains update
.
Cloud Code Log:
Input: {"original": { ... }, "update":{...}
I wonder if and how, we can access the original field to detect field changes before saving.
Please note that I have already tried several approaches to solve this without success:
- Using (object) .changedAttributes ()
- using (object) .previousAttributes ()
- selecting an existing object before updating it with new ones
Note in request.object.changedAttributes()
: Returns false
when used in beforeSave and afterSave - see below for details:
Log for before_save
- summarized for readability:
Input: { original: {units: '10'}, update: {units: '11'} }
Result: Update changed to { units: '11' }
[timestamp] false <--- console.log(request.object.changedAttributes())
Login for the appropriate after_save
:
[timestamp] false <--- console.log(request.object.changedAttributes())
source to share
There is a problem with changedAttributes()
. He seems to be answering false all the time - or at least beforeSave
where it is reasonably needed. (See here as well as other similar posts)
Here is a common challenge to do what has changed. Attributes should do.
// use underscore for _.map() since its great to have underscore anyway
// or use JS map if you prefer...
var _ = require('underscore');
function changesOn(object, klass) {
var query = new Parse.Query(klass);
return query.get(object.id).then(function(savedObject) {
return _.map(object.dirtyKeys(), function(key) {
return { oldValue: savedObject.get(key), newValue: object.get(key) }
});
});
}
// my mre beforeSave looks like this
Parse.Cloud.beforeSave("Dummy", function(request, response) {
var object = request.object;
var changedAttributes = object.changedAttributes();
console.log("changed attributes = " + JSON.stringify(changedAttributes)); // null indeed!
changesOn(object, "Dummy").then(function(changes) {
console.log("DIY changed attributes = " + JSON.stringify(changes));
response.success();
}, function(error) {
response.error(error);
});
});
When I change someAttribute
(column of numbers in instance Dummy
) from 32 to 1222 via client code or data browser the log shows this:
I2015-06-30T20: 22: 39.886Z] changed attributes = false
I2015-06-30T20: 22: 39.988Z] DIY made attributes = [{"OldValue": 32, "new_value": 1222}]
source to share