更新后,如何将模型实例与其以前的状态进行比较 [英] Upon updating, how to compare a model instance with its former state
问题描述
我正在使用Sails.js v0.10.5,但这可能适用于更通用的MVC生命周期逻辑(Ruby on Rails?).
I'm using Sails.js v0.10.5, but this probably applies to more general MVC lifecycle logics (Ruby on Rails?).
我有两个模型,例如Foo
和Baz
,它们通过一对一关联进行链接.
每次Foo
实例中的数据更改时,都必须在Baz
模型实例上执行一些繁重的操作,如下面显示的costlyRoutine
方法.
I have two models, say Foo
and Baz
, linked with a one-to-one association.
Each time that data in a Foo
instance changes, some heavy operations must be carried out on a Baz
model instance, like the costlyRoutine
method shown below.
// api/model/Foo.js
module.exports {
attributes: {
name: 'string',
data: 'json',
baz: {
model: 'Baz'
}
},
updateBaz: function(criteria,cb) {
Foo.findOne( criteria, function(err,foo) {
Baz.findOne( foo.baz, function(err,baz) {
baz.data = costlyRoutine( foo.data ); // or whatever
cb();
});
});
}
}
在更新Foo
的实例后,因此有必要首先测试data
是否已从旧对象更改为新对象.可能只是name
需要更新,在这种情况下,我想避免繁重的计算.
Upon updating an instance of Foo
, it therefore makes sense to first test whether data
has changed from old object to new. It could be that just name
needs to be updated, in which case I'd like to avoid the heavy computation.
什么时候最好进行检查?
When is it best to make that check?
我正在考虑beforeUpdate
回调,但是它将需要调用类似Foo.findOne(criteria)
的东西来检索当前的data
对象.效率低下?次优?
I'm thinking of the beforeUpdate
callback, but it will require calling something like Foo.findOne(criteria)
to retrieve the current data
object. Inefficient? Sub-optimal?
推荐答案
我能想到的唯一优化方法:
The only optimization I could think of:
如果相关字段正在更新,您可以致电
costlyRoutine
.
除此之外,您可以尝试缓存Foo
(使用引用缓存的某些局部性,例如分页).但这取决于您的用例.
Apart from that, you could try to cache Foo
(using some locality of reference caching, like paging). But that depends on your use case.
完美的优化实际上就像是试图展望未来:D
Perfect optimization would be really like trying to look into the future :D
这篇关于更新后,如何将模型实例与其以前的状态进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!