diff --git a/lib/model.js b/lib/model.js index a08badf4..b54863ad 100644 --- a/lib/model.js +++ b/lib/model.js @@ -278,7 +278,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { const type = properties[p].type; // Set default values - if (applyDefaultValues && propVal === undefined) { + if (applyDefaultValues && propVal === undefined && appliesDefaultsOnWrites(properties[p])) { let def = properties[p]['default']; if (def !== undefined) { if (typeof def === 'function') { @@ -362,6 +362,14 @@ ModelBaseClass.prototype._initProperties = function(data, options) { this.trigger('initialize'); }; +// Helper function for determing the applyDefaultOnWrites value of a property +function appliesDefaultsOnWrites(property) { + if (property && ('applyDefaultOnWrites' in property)) { + return property.applyDefaultOnWrites; + } + return true; +} + /** * Define a property on the model. * @param {String} prop Property name diff --git a/test/defaults.test.js b/test/defaults.test.js index d0c899e5..cc2b7ab3 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -99,5 +99,35 @@ describe('defaults', function() { should(found.color).be.undefined(); found.taste.should.equal('sweet'); }); + + it('removes nested property in an object when set to `false`', async () => { + const Apple = db.define('Apple', { + name: {type: String}, + qualities: { + color: {type: String, default: 'red', applyDefaultOnWrites: false}, + taste: {type: String, default: 'sweet'}, + }, + }, {applyDefaultsOnReads: false}); + + const apple = await Apple.create({name: 'Honeycrisp', qualities: {taste: 'sweet'}}); + const found = await Apple.findById(apple.id); + should(found.qualities.color).be.undefined(); + found.qualities.taste.should.equal('sweet'); + }); + + it('removes nested property in an array when set to `false', async () => { + const Apple = db.define('Apple', { + name: {type: String}, + qualities: [ + {color: {type: String, default: 'red', applyDefaultOnWrites: false}}, + {taste: {type: String, default: 'sweet'}}, + ], + }, {applyDefaultsOnReads: false}); + + const apple = await Apple.create({name: 'Honeycrisp', qualities: [{taste: 'sweet'}]}); + const found = await Apple.findById(apple.id); + should(found.qualities[0].color).be.undefined(); + found.qualities.length.should.equal(1); + }); }); });