0

I use objextion.js and knex on project.

And I wanna select two properties from relation and and nest them in an array. That relation contains array of object with properties lat and lng, I need receive array of arrays with lat and lng [[lat, lng]]. How I understand I must select fields and use raw from objection to write array_agg for contain my props, but I don't understand what syntax there must be.

In modifyGraph with select I receive array of objects with lng and lat

My request

const query = Restaurants
    .query()
    .withGraphFetched({
      schedule: true,
    })
    .skipUndefined();

  if (lat && lng) {
    query.withGraphFetched({
      areas: {
        area: {
          coordinates: true,
        },
      },
    }).modifyGraph('areas.area.coordinates', (builder) => {
      builder.select([
        'lat',
        'lng',
      ]);
    });
  }

  return query
    .andWhere(restFields)
    .andWhere('name', 'ilike', `%${search}%`);
};

My response from db

[
  AreasCoordinatesModel { lat: -46.653, lng: -23.543 },
  AreasCoordinatesModel { lat: -46.634, lng: -23.5346 },
]

And must be

[
 [ -46.653, -23.543 ],
 [ -46.634,-23.5346 ]
]
Drop
  • 1,394
  • 3
  • 15
  • 25
  • 1
    can't you write a custom JS function that takes the db response and converts it to what you need? – tHeSiD Jun 19 '20 at 20:11
  • @tHeSiD Unfortunately, after receiving this list, 2 nested cycles have already passed, I would not want to increase the number of cycles, I am sure that I can get my properties as an array from the database. – Drop Jun 19 '20 at 20:25
  • Implement it in the `afterFind` hook? https://vincit.github.io/objection.js/api/model/instance-methods.html#afterfind Or just create a specific method as @tHeSiD said – Rashomon Jun 25 '20 at 18:09

1 Answers1

0

you can map all the objects in the array on the return using

return (query
    .andWhere(restFields)
    .andWhere('name', 'ilike', `%${search}%`)).map(Object.values);

and it will return like you wanted.

Abed Murrar
  • 91
  • 1
  • 9