问题
The ultimate goal is to detect changes between an existing Parse object and the incoming update using the beforeSave
function in Cloud Code.
From the Cloud Code log available through parse.com, one can see the input to beforeSave
contains a field called original
and another one called update
.
Cloud Code log:
Input: {"original": { ... }, "update":{...}
I wonder if, and how, we can access the original field in order to detect changing fields before saving.
Note that I've already tried several approaches for solving this without success:
- using (object).changedAttributes()
- using (object).previousAttributes()
- fetching the existing object, before updating it with the new data
Note on request.object.changedAttributes()
:
returns false
when using in beforeSave and afterSave -- see below for more details:
Log for before_save
-- summarised for readability:
Input: { original: {units: '10'}, update: {units: '11'} }
Result: Update changed to { units: '11' }
[timestamp] false <--- console.log(request.object.changedAttributes())
Log for corresponding after_save
:
[timestamp] false <--- console.log(request.object.changedAttributes())
回答1:
There is a problem with changedAttributes()
. It seems to answer false all the time -- or at least in beforeSave
, where it would reasonably be needed. (See here, as well as other similar posts)
Here's a general purpose work-around to do what changedAttributes ought to 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
(a number column on a Dummy
instance) 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 changed attributes = [{"oldValue":32,"newValue":1222}]
来源:https://stackoverflow.com/questions/31100446/accessing-original-field-in-parse-com-cloud-code-beforesave-function