Skip to content

Commit 60f58d8

Browse files
committed
Adds aggregate .as() to define alias to previous function (#123)
Usually, when using .avg('age'), ORM will define an alias called avg_age to the returned value. If you want to change this do .avg('age').as('my_age').
1 parent c4a55dc commit 60f58d8

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/AggregateFunctions.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,17 @@ function AggregateFunctions(opts) {
4343
Array.prototype.slice.apply(arguments));
4444
return this;
4545
},
46+
as: function (alias) {
47+
if (aggregates.length === 0) {
48+
throw new Error("No aggregate function defined yet");
49+
}
50+
51+
var len = aggregates.length;
52+
53+
aggregates[len - 2][aggregates[len - 2].length - 1].alias = alias;
54+
55+
return this;
56+
},
4657
get: function (cb) {
4758
if (typeof cb != "function") {
4859
throw new Error("You must pass a callback to Model.aggregate().get()");
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
4+
common.createConnection(function (err, db) {
5+
common.createModelTable('test_aggregate', db.driver.db, function () {
6+
common.insertModelData('test_aggregate', db.driver.db, [
7+
{ id : 1, name : 'test1' },
8+
{ id : 2, name : 'test2' },
9+
{ id : 3, name : 'test3' },
10+
{ id : 4, name : 'test4' },
11+
{ id : 5, name : 'test5' }
12+
], function (err) {
13+
if (err) throw err;
14+
15+
var TestModel = db.define('test_aggregate', common.getModelProperties());
16+
17+
TestModel.aggregate({ id: common.ORM.gt(2) }).count('id').as('alias').get(function (err, alias) {
18+
assert.equal(err, null);
19+
assert.equal(alias, 3);
20+
db.close();
21+
});
22+
});
23+
});
24+
});

0 commit comments

Comments
 (0)