Skip to content

Commit

Permalink
feat: support applyDefaultOnWrites in nested properties
Browse files Browse the repository at this point in the history
Adds support for `applyDefaultOnWrites` in nested properties.
  • Loading branch information
Hage Yaapa committed Dec 12, 2019
1 parent bcd663b commit 9639e1a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/model.js
Expand Up @@ -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') {
Expand Down Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions test/defaults.test.js
Expand Up @@ -100,5 +100,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);
});
});
});

0 comments on commit 9639e1a

Please sign in to comment.