From eefe3a5d949d311149e214b7e3fc2caf6624d0a9 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Sat, 10 Aug 2013 15:12:55 +0200 Subject: [PATCH] Added modifier --- lib/model.js | 8 ++++++++ test/model.test.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/lib/model.js b/lib/model.js index 82a05d3..cd5de03 100644 --- a/lib/model.js +++ b/lib/model.js @@ -231,6 +231,14 @@ lastStepModifierFunctions.$set = function (obj, field, value) { }; +/** + * Unset a field + */ +lastStepModifierFunctions.$unset = function (obj, field, value) { + delete obj[field]; +}; + + /** * Push an element to the end of an array field */ diff --git a/test/model.test.js b/test/model.test.js index c260b8f..c503b53 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -296,6 +296,48 @@ describe('Model', function () { _.isEqual(modified, { yup: { subfield: 'changed', yop: 'yes indeed' }, totally: { doesnt: { exist: 'now it does' } } }).should.equal(true); }); }); // End of '$set modifier' + + describe('$unset modifier', function () { + + it('Can delete a field, not throwing an error if the field doesnt exist', function () { + var obj, updateQuery, modified; + + obj = { yup: 'yes', other: 'also' } + updateQuery = { $unset: { yup: true } } + modified = model.modify(obj, updateQuery); + assert.deepEqual(modified, { other: 'also' }); + + obj = { yup: 'yes', other: 'also' } + updateQuery = { $unset: { nope: true } } + modified = model.modify(obj, updateQuery); + assert.deepEqual(modified, obj); + + obj = { yup: 'yes', other: 'also' } + updateQuery = { $unset: { nope: true, other: true } } + modified = model.modify(obj, updateQuery); + assert.deepEqual(modified, { yup: 'yes' }); + }); + + it('Can unset sub-fields and entire nested documents', function () { + var obj, updateQuery, modified; + + obj = { yup: 'yes', nested: { a: 'also', b: 'yeah' } } + updateQuery = { $unset: { nested: true } } + modified = model.modify(obj, updateQuery); + assert.deepEqual(modified, { yup: 'yes' }); + + obj = { yup: 'yes', nested: { a: 'also', b: 'yeah' } } + updateQuery = { $unset: { 'nested.a': true } } + modified = model.modify(obj, updateQuery); + assert.deepEqual(modified, { yup: 'yes', nested: { b: 'yeah' } }); + + obj = { yup: 'yes', nested: { a: 'also', b: 'yeah' } } + updateQuery = { $unset: { 'nested.a': true, 'nested.b': true } } + modified = model.modify(obj, updateQuery); + assert.deepEqual(modified, { yup: 'yes', nested: {} }); + }); + + }); // End of '$unset modifier' describe('$inc modifier', function () { it('Throw an error if you try to use it with a non-number or on a non number field', function () {