From a6e0dc8ccd5ef430ef94aa3cb6f8851cccc6dd72 Mon Sep 17 00:00:00 2001 From: Eric Dobbertin Date: Sat, 28 Mar 2015 11:43:06 -0500 Subject: [PATCH] don't $unset when the prop is within an object that is already being $set; closes #301 --- simple-schema-tests.js | 18 ++++++++++++++++++ simple-schema.js | 7 ++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/simple-schema-tests.js b/simple-schema-tests.js index 7b4ed38..a3463d6 100644 --- a/simple-schema-tests.js +++ b/simple-schema-tests.js @@ -428,6 +428,19 @@ var reqCust = new SimpleSchema({ } }); +var optionalInObject = new SimpleSchema({ + requiredObj: { + type: Object + }, + 'requiredObj.optionalProp': { + type: String, + optional: true + }, + 'requiredObj.requiredProp': { + type: String + } +}); + /* * END SETUP FOR TESTS */ @@ -3046,6 +3059,11 @@ Tinytest.add("SimpleSchema - Clean", function(test) { true ); + // Don't $unset when the prop is within an object that is already being $set + myObj = {$set: {requiredObj: {requiredProp: 'blah', optionalProp: '' } }}; + optionalInObject.clean(myObj, {isModifier: true}); + test.equal(myObj, {$set: {requiredObj: {requiredProp: 'blah'} }}); + }); Tinytest.add("SimpleSchema - Clean - trimStrings", function(test) { diff --git a/simple-schema.js b/simple-schema.js index f64aa02..77f2988 100644 --- a/simple-schema.js +++ b/simple-schema.js @@ -740,7 +740,8 @@ SimpleSchema.prototype.clean = function(doc, options) { // For a document, we remove any fields that are being set to an empty string newVal = void 0; // For a modifier, we $unset any fields that are being set to an empty string - if (this.operator === "$set") { + if (this.operator === "$set" && this.position.match(/\[.+?\]/g).length < 2) { + p = this.position.replace("$set", "$unset"); mDoc.setValueForPosition(p, ""); } @@ -761,8 +762,8 @@ SimpleSchema.prototype.clean = function(doc, options) { if (options.removeEmptyStrings && (!this.operator || this.operator === "$set") && typeof val === "string" && !val.length) { // For a document, we remove any fields that are being set to an empty string this.remove(); - // For a modifier, we $unset any fields that are being set to an empty string - if (this.operator === "$set") { + // For a modifier, we $unset any fields that are being set to an empty string. But only if we're not already within an entire object that is being set. + if (this.operator === "$set" && this.position.match(/\[.+?\]/g).length < 2) { p = this.position.replace("$set", "$unset"); mDoc.setValueForPosition(p, ""); }