每当在这个模型上调用find时,我想在someModel中修改一个属性。由于我不能使用remote hooks,因为find不是一个远程方法,而是内置的,而且在操作钩子中,find/findOne只触发访问和加载钩子,而作为我的研究,它们不返回ctx中的模型实例(或者如果它们返回了,我想知道它们在哪里),所以我想做这样的事情:
modelName.observe('loaded', function (ctx, next) {
ctx.someModel_instance.updateAttribute(someCount, value
,function(err, instance){
if (err) next(err)
else{
console.log("done")
}
});
} 发布于 2019-06-27 10:28:40
的作用是:作为loaded不返回模型实例,但它返回ctx.data,其中它返回模型中数据的一个副本,如果您的模型中碰巧有一个唯一的ID,那么您可以通过findById获取模型实例,并且可以持久地访问/更改该模型的属性。例如:
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();
} );这将发挥作用,但问题将是不间断的递归,它造成的。因为findOne和updateAttribute将再次触发loaded hook,等等。这可以通过使用ctx.options字段来解决,该字段的作用类似于一个空容器,并可用于存储标志。例如:
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();
});https://stackoverflow.com/questions/56768855
复制相似问题