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")
}
});
}
Work Around: As
loadeddoes not return model instance but it does returnctx.data, in which it returns a copy of the data in your model, If you happen to have a uniqueIDin your model so you can fetch model instance byfindByIdand can persistently access/alter the attribute of the said model. e.g:This will do the trick, but the problem will be non-stop recursion that it causes. As
findOneandupdateAttributewill trigger theloaded hookagain and so on. This can be resolved by usingctx.optionsfield which acts like an empty container and can be used to store flags. e.g: