【发布时间】:2016-05-19 01:48:39
【问题描述】:
我在 /models/LocatableUser.js 中尝试使用的钩子中的总体目标是确定是否有需要更新的实际更改,如果有,请执行某些操作(制作另一个 api称呼)。
我有一个继承自该自定义模型的自定义模型结构,因此在父模型中定义 before save 挂钩时,它适用于两个子模型。这是我在父模型LocatableUser中定义的方法的示例:
LocatableUser.observe('before save', function (ctx, next) {
if (ctx.instance){ // new record
ctx.instance._address.getGeopoint(function (error, location) {
setLocation(error, location, ctx.instance, next);
});
} else if (ctx.currentInstance) { // this is an update, currentInstance is treated as immutable
LocatableUser.findById(ctx.currentInstance.id, function(err, data) {
console.log('Locatable User: current data is: ', err, data)
})
console.log('Locatable User: ctx is:', ctx);
ctx.currentInstance._address.getGeopoint(function (error, location) {
setLocation(error, location, ctx.data, next);
});
} else {
console.warn('no context instance');
}
});
这段代码的问题是,由于没有LocatableUser 的具体类,调用LocatableUser.findById() 不会找到任何东西,因为实际的类将是LocatableUser 的某个子类。我发现唯一可行的方法是在两个子类中定义此方法,但这会重复代码。
有没有办法从LocatableUser 类调用派生类的findById 方法?
环回版本 2.22.0
【问题讨论】:
-
如果你看一下 ctx,你能弄清楚实际使用的类吗?
-
仔细观察,在 ctx.Model.definition 中确实有一个类名字段...但这可能是比我尝试做的更好的方法
标签: loopbackjs