最终目标是使用以下方法检测现有 Parse 对象和传入更新之间的更改beforeSave
云代码中的函数。
从 parse.com 提供的 Cloud Code 日志中,我们可以看到以下内容的输入:beforeSave
包含一个名为original
另一个叫update
.
云代码日志:
Input: {"original": { ... }, "update":{...}
我想知道我们是否以及如何访问原始字段以便在保存之前检测更改的字段。
请注意,我已经尝试了多种方法来解决此问题,但没有成功:
- 使用 (object).changedAttributes()
- 使用 (object).previousAttributes()
- 在使用新数据更新现有对象之前获取现有对象
Note on request.object.changedAttributes()
:
回报false
在 beforeSave 和 afterSave 中使用时 - 请参阅下文了解更多详细信息:
Log for 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())
There is有问题changedAttributes()
。它似乎总是回答错误——或者至少在beforeSave
,在合理需要的地方。 (看here https://www.parse.com/questions/how-to-get-the-changed-attribute-value-beforesave,以及其他类似的帖子)
这是一个通用的解决方法,可以完成 ChangedAttributes 应该做的事情。
// 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);
});
});
当我改变时someAttribute
(a 上的数字列Dummy
通过客户端代码或数据浏览器从 32 到 1222 实例),日志显示如下:
I2015-06-30T20:22:39.886Z]更改属性 = false
I2015-06-30T20:22:39.988Z]DIY改变属性=
[{“oldValue”:32,“newValue”:1222}]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)