From 464610ef0ab5f6463ddda90e6384a487e0ee621f Mon Sep 17 00:00:00 2001 From: Hage Yaapa Date: Mon, 19 Aug 2019 17:11:27 +0530 Subject: [PATCH] feat: add applyDefaultOnWrites property Adds the ability to ignore writing default values to the database. --- lib/dao.js | 15 +++++++++++++++ test/defaults.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/dao.js b/lib/dao.js index 4db12e8d..b77e83d5 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 68cf9872..d0c899e5 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -75,4 +75,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'); + }); + }); });