Search code examples
javascriptnode.jsloopbackjsstrongloop

Getting sum() of an attribute in loopback without looping through all instances of the object


I have a model DummyModel that has the attributes attOne, attTwo and attThree.

To get all the instances of attOne, one can use-

DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });

The above query corresponds more or less to the MySQL query -

select attOne from DummyModel where attTwo = 'someValue'

However, I need to find the sum of all the attOne values returned from the above query. That is, the MySQL equivalent of -

select sum(attOne) from DummyModel where attTwo = 'someValue'

I read that loopback doesn't support aggregrate functions (i.e. groupby). But is there any way to getsum(attOne)?

I know one way is to get the object and then loop over all the instances and add it.

What I want to know is if there's any pre-existing loopback method to do the same.


Solution

  • Supposing that this code

    f = DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });
    

    returns an array like this

    [
    {attTwo: 'someValue' ,attOne: 1}
    {attTwo: 'otherValue',attOne: 1}
    ]
    

    you can use the reduce function to apply a function to all elements

    var sum = f.reduce(function(last, d) {return d.attOne + last},0);
    

    And here is the working code

    DummyModel = {
      find: function(a) {
        return [{
          attTwo: 'someValue',
          attOne: 1
        }, {
          attTwo: 'otherValue',
          attOne: 2
        }];
      }
    }
    
    f = DummyModel.find({
      where: {
        attTwo: 'someValue'
      },
      fields: {
        attOne: true
      }
    });
    
    sum = f.reduce(function(last, d) {
      return d.attOne + last;
    }, 0);
    
    alert(sum);