loopbackjs - Loopback:如何在 afterRemote 中访问关系
问题描述
我为仓库模型设置了以下 afterRemote 方法:
Depot.afterRemote('find', function(context, depots, next) {
context.result.forEach(depot => {
console.log(depot.drivers);
depot.address = depot.street_name + ' ' + depot.door_number;
depot.driver_count = depot.drivers.length;
});
next()
})
在 json 响应中 depot.drivers 包含正确的数据。
但是,当我尝试在上述方法中访问 depot.drivers 时,会得到一些奇怪的输出:
{ [Function: f]
_receiver: { postal_code: '1216BS',
door_number: '3',
street_name: 'Straat naam',
city: 'Hilversum',
lat: null,
lng: null,
created: 2018-04-03T01:49:12.000Z,
id: 23,
distributor_id: 2,
distributor: { sys_id: 1,
name: 'distributeur naam',
contact_person: 'Persoon B',
phone: '000-000000',
email: 'info@d.nl',
created: 2018-03-06T00:22:33.000Z,
id: 2 },
drivers: List [] },
_scope: { where: { hub_id: 23 } },
_targetClass: 'driver',
find: [Function],
getAsync: [Function],
build: [Function: bound method],
create: [Function: bound method],
updateAll: [Function: updateAll],
destroyAll: [Function: destroyAll],
findById: [Function: bound method],
findOne: [Function: findOne],
count: [Function: count],
destroy: [Function: bound method],
updateById: [Function: bound method],
exists: [Function: bound method] }
我最终想添加一个 depot.drivers_count 属性,这样我就可以在前端表中显示连接到特定仓库的驱动程序数量。
任何人都知道如何做到这一点?
解决方案
看起来数据没有转换为 JSON。
我会试试这个:
context.result.forEach(depot => {
depot = depot.toJSON();
console.log(depot.drivers);
depot.address = depot.street_name + ' ' + depot.door_number;
depot.driver_count = depot.drivers.length;
});
推荐阅读
- php - 如何使用 PHP 发送包含 youtube 视频的电子邮件
- azure - 应用程序网关 URL 路由到多个应用程序服务
- python - 编写python函数时的自动弹出参数方法和属性
- android - 无法在 Anko 中预览
- regex - 如何使用 RegEx 匹配这个?
- python - 在我尝试使用 Python 中的快速排序算法时遇到递归问题
- python - 以编程方式查找为给定 PID 打开的端口
- renderscript - 偶尔的 RenderScript 加载失败 - ScriptC 脚本加载失败
- c++ - 使用 clang 编译的 Android 上的 Qt 在共享库上的 dynamic_cast 失败
- r - 在 R 中为 JSON 添加括号