Search code examples
javascriptloopbackjsloopback

How to push the result from a loopback findById method into ctx.result


I am able to push the result from inside the findById function and also the log prints correctly, but outside the forEach loop it is just empty. I did try to use promise but that also did not work.

let finalData = [];
Model.afterRemote('find', function(ctx, instance, next) {
  if (ctx.result) {
    if (Array.isArray(ctx.result)) {
      ctx.result.forEach(function(result) {
        Model.findById(result.id, {
            include: {
              relation: 'users',
              scope: {
                fields: ['email']
              }
            }
          },
          function(err, response) {
            finalData.push(response);
            console.log(finalData); // has the user information
          });
      });
    }
    ctx.result = finalData;
    console.log(ctx.result); // --> empty result (need the finalData result)
  }
  next();
});


Solution

  • Why don't you call the remote method using a filter? Your way brings to N+1 queries which are very inefficient. There is no need to implement a afterRemote in your use case. Use the following filter in your API call:

    {
      "include": {
        "relation": "users",
        "scope": {
          "fields": ["email"]
        }
      }
    }