LoopBack "group by" ability with mySQL?
Asked Answered
P

1

6

I'm new to LoopBack, and I seem to be missing something. I've heard so much about StrongLoop and LoopBack, I find it hard to believe this doesn't exist.

My case: I'm looking to count the amount of events with each different severity.

A table for example:

EventID | Severity

1 | 2

2 | 2

3 | 4

4 | 3

5 | 3

6 | 5

7 | 1

8 | 2

Now I want to count the amount of events and group them by severity, so I get something like this JSON back:

{1:1, 2:3, 3:2, 4:1, 5:1} *(severity:count)*

With SQL it's quite simple, just use "SELECT severity, count(severity) FROM events GROUP BY severity".

I have researched this for a while, and still can't believe this simple thing can't be done with LoopBack!

Any solution? Or maybe an article to point me to?

Thanks in advance!

Panegyric answered 17/2, 2016 at 12:20 Comment(0)
M
4

Well Loopback ORM as of this moment doesn't have support for it completely but you can always use the MySQL driver directly:

YourModel.dataSource.connector.query('SELECT severity, count(severity) FROM events GROUP BY severity', (err, results) => {
   //...
});

But if you want to be database agnostic, you can do it in Javascript with Lodash:

YourModel.find({ fields: 'severity' }).then(rows => {
  const results = _.mapValues(_.groupBy(rows, severity), 'length');
  //...
});
Messroom answered 26/11, 2016 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.