LoopBack "group by" ability with mySQL?

I'm new to LoopBack , and it seems to me that something is missing. I've heard so much about StrongLoop and LoopBack , it's hard for me to believe that this does not exist.

My case: I am looking to count the number of events with each severity.

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 number 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 pretty simple, just use "SELECT severity, count(severity) FROM events GROUP BY severity" .

I researched this for a while and still can’t believe that this simple thing cannot be done with LoopBack !

Any solution? Or maybe an article on which I need to point out?

Thanks in advance!

+5
source share
1 answer

Well Loopback ORM does not fully support it from now on, 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 a database agnostic, you can do it in Javascript with Lodash:

 YourModel.find({ fields: 'severity' }).then(rows => { const results = _.mapValues(_.groupBy(rows, severity), 'length'); //... }); 
+2
source

Source: https://habr.com/ru/post/1243221/


All Articles