diff --git a/lib/dao.js b/lib/dao.js index d39e3504..69432f5d 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -431,6 +431,8 @@ DataAccessObject.create = function(data, options, cb) { }); } + val = applyDefaultsOnWrites(val, Model.definition); + context = { Model: Model, data: val, @@ -452,6 +454,19 @@ DataAccessObject.create = function(data, options, cb) { return cb.promise; }; +// Implementation of applyDefaultOnWrites property +function applyDefaultsOnWrites(obj, modelDefinition) { + for (const key in modelDefinition.properties) { + const prop = modelDefinition.properties[key]; + if ('applyDefaultOnWrites' in prop && !prop.applyDefaultOnWrites && + prop.default !== undefined && prop.default === obj[key]) { + delete obj[key]; + } + } + + return obj; +} + function stillConnecting(dataSource, obj, args) { if (typeof args[args.length - 1] === 'function') { return dataSource.ready(obj, args); diff --git a/test/defaults.test.js b/test/defaults.test.js index c0503c71..931ed7d1 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -76,4 +76,29 @@ describe('defaults', function() { }); }); }); + + context('applyDefaultOnWrites', function() { + it('does not affect default behavior when not set', async () => { + const Apple = db.define('Apple', { + color: {type: String, default: 'red'}, + taste: {type: String, default: 'sweet'}, + }, {applyDefaultsOnReads: false}); + + const apple = await Apple.create(); + apple.color.should.equal('red'); + apple.taste.should.equal('sweet'); + }); + + it('removes the property when set to `false`', async () => { + const Apple = db.define('Apple', { + color: {type: String, default: 'red', applyDefaultOnWrites: false}, + taste: {type: String, default: 'sweet'}, + }, {applyDefaultsOnReads: false}); + + const apple = await Apple.create({color: 'red', taste: 'sweet'}); + const found = await Apple.findById(apple.id); + should(found.color).be.undefined(); + found.taste.should.equal('sweet'); + }); + }); });