Skip to content

Commit

Permalink
Merge pull request #5740 from AyushG3112/addFields-aggregate-feature
Browse files Browse the repository at this point in the history
Add $addFields pipeline operator via a Mongoose Function
  • Loading branch information
vkarpov15 authored Oct 25, 2017
2 parents 06f39e8 + cc41aa2 commit 62e2ff6
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 17 deletions.
35 changes: 35 additions & 0 deletions lib/aggregate.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,41 @@ Aggregate.prototype.append = function() {
return this;
};

/**
* Appends a new $addFields operator to this aggregate pipeline.
* Requires MongoDB v3.4+ to work
*
* ####Examples:
*
* // adding new fields based on existing fields
* aggregate.addFields({
* newField: '$b.nested'
* , plusTen: { $add: ['$val', 10]}
* , sub: {
* name: '$a'
* }
* })
*
* // etc
* aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });
*
* @param {Object} arg field specification
* @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.addFields = function(arg) {
var fields = {};
if (typeof arg === 'object' && !util.isArray(arg)) {
Object.keys(arg).forEach(function(field) {
fields[field] = arg[field];
});
} else {
throw new Error('Invalid addFields() argument. Must be an object');
}
return this.append({$addFields: fields});
};

/**
* Appends a new $project operator to this aggregate pipeline.
*
Expand Down
34 changes: 17 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions test/aggregate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,19 @@ describe('aggregate: ', function() {
});
});

describe('addFields', function() {
it('(object)', function(done) {
var aggregate = new Aggregate();

assert.equal(aggregate.addFields({ a: 1, b: 1, c: 0 }), aggregate);
assert.deepEqual(aggregate._pipeline, [{ $addFields: { a: 1, b: 1, c: 0 } }]);

aggregate.addFields({ d: {$add: ['$a','$b']} });
assert.deepEqual(aggregate._pipeline, [{ $addFields: { a: 1, b: 1, c: 0 } }, { $addFields: { d: {$add: ['$a','$b']} } }]);
done();
});
});

describe('facet', function() {
it('works', function(done) {
var aggregate = new Aggregate();
Expand Down

0 comments on commit 62e2ff6

Please sign in to comment.