Docs incorrect? Observe "loaded" returns instance, not data
On this page in the docs it says that observing loaded will return a context with data in it. However that doesn't seem to be case when I am testing it, instead giving the model instance:
AlertRule.observe("loaded", function(ctx, next) {
debug("loaded alert rule")
debug(Object.keys(ctx))
debug(ctx.data)
debug(ctx.instance)
//....
Gives this output:
api:models loaded alert rule +8ms
api:models [ 'Model', 'instance', 'isNewInstance', 'hookState', 'options' ] +0ms
api:models undefined +0ms
api:models { type: 'deviation', path: '/dosers/1/reading/ec', data: { upper: 1, lower: 0.5 }, dash_id: 1, active: false, id: 1 } +1ms
Do the docs need updating?
@crandmck ^
I don't think if there is any doc issue. @penguinpowernz Could you please clarify what method you are referring to that loaded hook returns instance and not data?
AFAICT, all loaded hooks return data and not instance. Please see loaded hook for create, loaded hook for updateORCreate and you can see all of the other loaded hooks in https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/dao.js
@Amir-61 Noticed the same behaviour in my code. Just updated to Strongloop 6.0.2, and using Loopback v2.34.1 (we were using the alpha-2 release, but decided to use official releases instead)
ModelName.observe('loaded', (ctx, next)=>{
if(ctx.data){
// The data property exists when saving a new model instance. No instance property.
}
if(ctx.instance){
// instance exists when querying data from the database. No data property. It's either one or the other
}
next();
});
Thanks @frankmalin,
To make it clear and easier for @crandmck (our doc expert) I believe just find* methods (find, findOne, findById and findByIds) have instance in their loaded OH. All other methods provide data object in their loaded OH.
Thanks for confirming that @frankorama. Any more info needed from my side?
reported same bug a while ago #1071. It's supposed to be fixed in 3.x but not backported to 2.x due to suspected breaking changes
reported same bug a while ago #1071. It's supposed to be fixed in 3.x but not backported to 2.x due to suspected breaking changes
I believe you are right! IIRC It was fixed a while ago for LB 3.x https://github.com/strongloop/loopback-datasource-juggler/pull/796 by @bajtos.
@crandmck So When we document https://github.com/strongloop/loopback/issues/2778#issuecomment-248963090 we should mention thats the 2.x version behaviour and it is fixed now in LB 3.x. We could not backport it because it was a breaking change in 2.x.
Thanks @benkroeger for chiming in 👍
Added a note to http://loopback.io/doc/en/lb2/Operation-hooks.html#loaded (v 2.x only).