Subburaj Subburaj - 6 months ago 63
Node.js Question

Remote hooks in loopback

In loopback i am using

afterRemote
hook for get request as follows

Modelname.afterRemote("**", function(ctx, expenses, next){
if(ctx.method.name == 'find') {
for(var i=0; i<ctx.result.length; i++){
delete ctx.result[i].category;
}
}
});


In the above i am trying to delete a key from get Request response before sending to client. But still that appears. SO its not possible to delete a key which we have created in model.json?. Please share your ideas. Thanks in advance.

Answer

You need to use result.unsetAttribute('field')

Modelname.afterRemote("**", function(ctx, expenses, next){
  if(ctx.method.name == 'find') {
    for(var i = 0; i < ctx.result.length; i++) {
      ctx.result[i].unsetAttribute('category');
    }
  }
});

Here is a related GitHub issue, in case you are interested.

It is documented in the Operation hooks section of a LoopBack documentation, but there is sadly no mention of it in the Remote hooks section.

Note: If you want to restrict this hook to only find method, you can specify it with Modelname.afterRemote("find", function (ctx, expenses, next) {});.