Skip to content Skip to sidebar Skip to footer

Accessing Original Field In Parse.com Cloud Code BeforeSave Function

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 throu

Solution 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}]


Post a Comment for "Accessing Original Field In Parse.com Cloud Code BeforeSave Function"