Skip to content

Commit

Permalink
New modifier
Browse files Browse the repository at this point in the history
  • Loading branch information
louischatriot committed Jun 19, 2013
1 parent 122cea5 commit f6b764d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,17 @@ lastStepModifierFunctions.$push = function (obj, field, value) {
obj[field].push(value);
};

// Add an element to an array field only if it is not already in it
// No modification if the element is already in the array
// Note that it doesn't check whether the original array contains duplicates
lastStepModifierFunctions.$addToSet = function (obj, field, value) {
// Create the array if it doesn't exist
if (!obj.hasOwnProperty(field)) { obj[field] = []; }

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

// Increment a numeric field's value
lastStepModifierFunctions.$inc = function (obj, field, value) {
if (typeof value !== 'number') { throw value + " must be a number"; }
Expand Down
33 changes: 33 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,39 @@ describe('Model', function () {

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

describe('$addToSet modifier', function () {

it('Can add an element to a set', function () {
var obj = { arr: ['hello'] }
, modified;

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

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

it('Can add an element to a non-existent set and will create the array', function () {
var obj = { arr: [] }
, modified;

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

it('Throw if we try to addToSet to a non-array', function () {
var obj = { arr: 'hello' }
, modified;

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

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

}); // ==== End of 'Modifying documents' ==== //


Expand Down

0 comments on commit f6b764d

Please sign in to comment.