feat: applyDefaultOnWrites in nested properties
Adds support for `applyDefaultOnWrites` in nested properties.
This commit is contained in:
parent
bcd663b75f
commit
f9a5c44dba
10
lib/model.js
10
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
|
||||
|
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue