modifier works with

pull/2/head
Louis Chatriot 12 years ago
parent e30cc58e5e
commit 05d9ad9e5f
  1. 10
      lib/model.js
  2. 18
      test/model.test.js

@ -239,7 +239,17 @@ lastStepModifierFunctions.$push = function (obj, field, value) {
if (!obj.hasOwnProperty(field)) { obj[field] = []; }
if (!util.isArray(obj[field])) { throw "Can't $push an element on non-array values"; }
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"; }
value.$each.forEach(function (v) {
obj[field].push(v);
});
} else {
obj[field].push(value);
}
};

@ -344,7 +344,7 @@ describe('Model', function () {
});
it('Can push an element to a non-existent field and will create the array', function () {
var obj = { arr: [] }
var obj = {}
, modified;
modified = model.modify(obj, { $push: { arr: 'world' } });
@ -377,6 +377,22 @@ describe('Model', function () {
}).should.throw();
});
it('Can use the $each modifier to add multiple values to an array at once', function () {
var obj = { arr: ['hello'] }
, modified;
modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'] } } });
assert.deepEqual(modified, { arr: ['hello', 'world', 'earth', 'everything'] });
(function () {
modified = model.modify(obj, { $push: { arr: { $each: 45 } } });
}).should.throw();
(function () {
modified = model.modify(obj, { $push: { arr: { $each: ['world'], unauthorized: true } } });
}).should.throw();
});
}); // End of '$push modifier'
describe('$addToSet modifier', function () {

Loading…
Cancel
Save