我在鉤子中的總體目標我試圖在我的/models/LocatableUser.js中使用這裏是找出是否有我需要更新的實際更改,如果有是,做點什麼(做另一個API調用)。Loopback:檢測模型中的變化
我有一個繼承自此自定義模型的自定義模型的結構,因此它在父模型中定義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
的一些小孩班。我發現唯一可行的是在兩個子類中定義這個方法,但是它重複了代碼。
有沒有辦法讓派生類的findById
方法調用LocatableUser
類?
迴環版本2.22.0
如果你看看ctx,你能找出正在使用的實際班級嗎? –
經過仔細檢查,它看起來好像在ctx.Model.definition中有一個類名稱字段......但這可能是比我想要做的更好的方法 – BrDaHa