Use deep equality to know whether we can addToSet or not

pull/2/head
Louis Chatriot 12 years ago
parent f0a8dcb708
commit e30cc58e5e
  1. 2
      lib/datastore.js
  2. 9
      lib/model.js
  3. 12
      test/model.test.js

@ -589,4 +589,6 @@ Datastore.prototype.remove = function () {
module.exports = Datastore;

@ -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); }
};

@ -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 () {

Loading…
Cancel
Save