Reputation: 126
I want to alter an attribute in someModel, whenever a find is called over this model. As I can't use remote Hooks as find is not a remote method, rather built in, and in operational hooks find/findOne only trigger access and loaded hooks, and as my research, they do not return the model instance in their ctx (or if they do, I would like to know where), I want to do something like:
modelName.observe('loaded', function (ctx, next) {
ctx.someModel_instance.updateAttribute(someCount, value
,function(err, instance){
if (err) next(err)
else{
console.log("done")
}
});
}
Upvotes: 0
Views: 186
Reputation: 126
Work Around:
As loaded
does not return model instance but it does return ctx.data
, in which it returns a copy of the data in your model, If you happen to have a unique ID
in your model so you can fetch model instance by findById
and can persistently access/alter the attribute of the said model. e.g:
modelName.observe('loaded', function (ctx, next) {
modelName.findOne({
where: {id : ctx.data.id},
},function(err, someModel_instance){
if (err) next(err)
else{
someModel_instance.updateAttribute(someCount,value
, function(err, instance){
console.log(done)
});
}
});
next();
} );
This will do the trick, but the problem will be non-stop recursion that it causes. As findOne
and updateAttribute
will trigger the loaded hook
again and so on. This can be resolved by using ctx.options
field which acts like an empty container and can be used to store flags. e.g:
modelName.observe('loaded', function (ctx, next) {
if(ctx.options && !ctx.options.alreadyFound){
modelName.findOne({
where: {id : ctx.data.id},
},{alreadyFound = true}, function(err, someModel_instance){
if (err) next(err)
else{
someModel_instance.updateAttribute(someCount,value
,{alreadyFound = true}, function(err, instance){
console.log(done)
});
}
});
}
next();
});
Upvotes: 0