【问题标题】:How to push the result from a loopback findById method into ctx.result如何将环回 findById 方法的结果推送到 ctx.result
【发布时间】:2019-02-28 22:01:24
【问题描述】:

我能够从 findById 函数内部推送结果,并且日志打印正确,但在 forEach 循环之外它只是空的。我确实尝试过使用 Promise,但这也没有用。

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();
});

【问题讨论】:

  • 我发现第一个get请求是空的,但是后面的get请求返回正确的数据。

标签: javascript loopbackjs loopback


【解决方案1】:

为什么不使用过滤器调用远程方法?您的方式带来了非常低效的 N+1 个查询。无需在您的用例中实现 afterRemote。在您的 API 调用中使用以下过滤器:

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

【讨论】:

  • 是的,你是对的。我注意到后续请求的结果数量有所增加。
  • 只是对过滤器的小改动,必须用双引号将字符串括起来。
【解决方案2】:

您需要了解异步函数和命令顺序。

虽然我认为您可以对您的 API 进行不同的查询来实现您的需求。

但无论如何,我会这样称呼你的函数:

Model.afterRemote('find', function(ctx, instance, next) {
  let finalData = [];
  if (ctx.result) {
    if (Array.isArray(ctx.result)) {
      // map your results to array of id's
      const ids = ctx.result.map(res => res.id);
      // get result with different search query
      const response = await Arscenes.find({where: {id: {inq: ids}}}, {
          include: [{
            relation: 'users',
            scope: {
              fields: ['email']
            }
          }]
        });
        // put the reuslts in ctx.result
      ctx.result = response;
      // call next() to end the call
      next();
    }
  } else {
    // call next() to end the call only in else case, in your example you're calling that before anything else so the request is over
    next();
  }

});

【讨论】:

  • 我修改了您的代码以使用 promise,但返回的 val 不包括用户。
  • 对不起,出错了,现在应该可以了(过滤器错误,应该是:`{where: {...}, include: [{...}]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多