Skip to content

Commit

Permalink
Adds possibility of order to aggregate method (#114)
Browse files Browse the repository at this point in the history
  • Loading branch information
dresende committed Apr 11, 2013
1 parent 4cee44e commit 84a2c36
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/AggregateFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ function AggregateFunctions(opts) {
group_by = Array.prototype.slice.apply(arguments);
return this;
},
order: function (property, order) {
opts.order = [ property, order ];
return this;
},
get: function (cb) {
if (typeof cb != "function") {
throw new Error("You must pass a callback to Model.aggregate().get()");
Expand All @@ -56,6 +60,10 @@ function AggregateFunctions(opts) {
query.groupBy.apply(query, group_by);
}

if (opts.order) {
query.order.apply(query, opts.order);
}

opts.driver.execQuery(query.build(), function (err, data) {
if (err) {
return cb(err);
Expand Down
28 changes: 28 additions & 0 deletions test/integration/test-aggregate-groupby-orderby.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
var common = require('../common');
var assert = require('assert');

common.createConnection(function (err, db) {
common.createModelTable('test_aggregate_groupby_orderby', db.driver.db, function () {
common.insertModelData('test_aggregate_groupby_orderby', db.driver.db, [
{ id : 2, name : 'test1' },
{ id : 3, name : 'test1' },
{ id : 4, name : 'test1' },
{ id : 5, name : 'test2' }
], function (err) {
if (err) throw err;

var TestModel = db.define('test_aggregate_groupby_orderby', common.getModelProperties());

TestModel.aggregate().avg('id').count().groupBy('name').order('name', 'Z').get(function (err, rows) {
assert.equal(err, null);
assert.equal(Array.isArray(rows), true);
assert.equal(rows.length, 2);
assert.equal(rows[0].avg_id, 5);
assert.equal(rows[0].count, 1);
assert.equal(rows[1].avg_id, 3);
assert.equal(rows[1].count, 3);
db.close();
});
});
});
});

0 comments on commit 84a2c36

Please sign in to comment.