首页 文章

访问Parse.com Cloud Code之前的原始字段保存功能

提问于
浏览
3

最终目标是使用Cloud Code中的 beforeSave 函数检测现有Parse对象与传入更新之间的更改 .

从parse.com提供的Cloud Code日志中,可以看到 beforeSave 的输入包含一个名为 original 的字段和另一个名为 update 的字段 .

Cloud 代码日志:

Input: {"original": { ... }, "update":{...}

我想知道是否以及如何访问原始字段以便在保存之前检测更改字段 .

请注意,我已经尝试了几种解决方法而没有成功的方法:

  • using(object).changedAttributes()

  • using(object).previousAttributes()

  • 在使用新数据更新之前获取现有对象

关于 request.object.changedAttributes() 的注释:在beforeSave和afterSave中使用时返回 false - 有关更多详细信息,请参见下文:

记录 before_save - 为了便于阅读而进行了总结:

Input: { original: {units: '10'}, update: {units: '11'} }
Result: Update changed to { units: '11' }
[timestamp] false <--- console.log(request.object.changedAttributes())

记录相应的 after_save

[timestamp] false <--- console.log(request.object.changedAttributes())

1 回答

  • 2

    changedAttributes() 有问题 . 它似乎总是回答错误 - 或至少在 beforeSave ,它将合理地需要 . (见here,以及其他类似帖子)

    这是一个通用的解决方法来做changeAttributes应该做的事情 .

    // 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);
        });
    });
    

    当我通过客户端代码或数据浏览器将 someAttributeDummy 实例上的数字列)从32更改为1222时,日志显示如下:

    I2015-06-30T20:22:39.886Z]已更改属性= false I2015-06-30T20:22:39.988Z] DIY已更改属性= [{“oldValue”:32,“newValue”:1222}]

相关问题