From e30cc58e5ec9cbe0aa0d4ff25a1f37792c9a8946 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Fri, 21 Jun 2013 18:17:34 +0200 Subject: [PATCH] Use deep equality to know whether we can addToSet or not --- lib/datastore.js | 2 ++ lib/model.js | 9 ++++++++- test/model.test.js | 12 ++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/datastore.js b/lib/datastore.js index e2350f4..69165fd 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -589,4 +589,6 @@ Datastore.prototype.remove = function () { + + module.exports = Datastore; diff --git a/lib/model.js b/lib/model.js index 7bca16b..709cf06 100644 --- a/lib/model.js +++ b/lib/model.js @@ -249,11 +249,18 @@ lastStepModifierFunctions.$push = function (obj, field, value) { * Note that it doesn't check whether the original array contains duplicates */ lastStepModifierFunctions.$addToSet = function (obj, field, value) { + var addToSet = true; + // 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); } + + obj[field].forEach(function (v) { + if (compareThings(v, value) === 0) { addToSet = false; } + }); + + if (addToSet) { obj[field].push(value); } }; diff --git a/test/model.test.js b/test/model.test.js index 167a0ed..e1ef87a 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -410,6 +410,18 @@ describe('Model', function () { }).should.throw(); }); + it('Use deep-equality to check whether we can add a value to a set', function () { + var obj = { arr: [ { b: 2 } ] } + , modified; + + modified = model.modify(obj, { $addToSet: { arr: { b: 3 } } }); + assert.deepEqual(modified, { arr: [{ b: 2 }, { b: 3 }] }); + + obj = { arr: [ { b: 2 } ] } + modified = model.modify(obj, { $addToSet: { arr: { b: 2 } } }); + assert.deepEqual(modified, { arr: [{ b: 2 }] }); + }); + }); // End of '$addToSet modifier' describe('$pop modifier', function () {