Skip to content

Commit

Permalink
Can use with
Browse files Browse the repository at this point in the history
  • Loading branch information
louischatriot committed Jun 21, 2013
1 parent c88e081 commit 7a89cc8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,19 @@ lastStepModifierFunctions.$addToSet = function (obj, field, value) {

if (!util.isArray(obj[field])) { throw "Can't $addToSet an element on non-array values"; }

obj[field].forEach(function (v) {
if (compareThings(v, value) === 0) { addToSet = false; }
});
if (value !== null && typeof value === 'object' && value.$each) {
if (Object.keys(value).length > 1) { throw "Can't use another field in conjunction with $each"; }
if (!util.isArray(value.$each)) { throw "$each requires an array value"; }

if (addToSet) { obj[field].push(value); }
value.$each.forEach(function (v) {
lastStepModifierFunctions.$addToSet(obj, field, v);
});
} else {
obj[field].forEach(function (v) {
if (compareThings(v, value) === 0) { addToSet = false; }
});
if (addToSet) { obj[field].push(value); }
}
};


Expand Down
16 changes: 16 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,22 @@ describe('Model', function () {
assert.deepEqual(modified, { arr: [{ b: 2 }] });
});

it('Can use the $each modifier to add multiple values to a set at once', function () {
var obj = { arr: ['hello'] }
, modified;

modified = model.modify(obj, { $addToSet: { arr: { $each: ['world', 'earth', 'hello', 'earth'] } } });
assert.deepEqual(modified, { arr: ['hello', 'world', 'earth'] });

(function () {
modified = model.modify(obj, { $addToSet: { arr: { $each: 45 } } });
}).should.throw();

(function () {
modified = model.modify(obj, { $addToSet: { arr: { $each: ['world'], unauthorized: true } } });
}).should.throw();
});

}); // End of '$addToSet modifier'

describe('$pop modifier', function () {
Expand Down

0 comments on commit 7a89cc8

Please sign in to comment.