Search code examples
loopbackjs

Loopback: How to access relationship in an afterRemote


I have the following afterRemote method setup for the depot model:

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

In the json response depot.drivers contains proper data.

However when I try to access depot.drivers in the above method I get some weird output:

{ [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] }

I would eventually like to add a depot.drivers_count property so I can display the amount of drivers connected to a specific depot in a front-end table.

Anyone has an idea how to do this?


Solution

  • Looks like the datas are not converted to JSON.

    I would try this:

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