From e7a108efdb01783260c5176ea77f62bb7b09ac84 Mon Sep 17 00:00:00 2001 From: Fabien Franzen Date: Sun, 19 Oct 2014 18:47:27 +0200 Subject: [PATCH] Don't apply defaults when fields are specified --- lib/model.js | 31 ++++++++++++++++++++++++++----- test/defaults.test.js | 14 ++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/lib/model.js b/lib/model.js index 7e7a66f2..533b9693 100644 --- a/lib/model.js +++ b/lib/model.js @@ -53,7 +53,7 @@ function ModelBaseClass(data, options) { ModelBaseClass.prototype._initProperties = function (data, options) { var self = this; var ctor = this.constructor; - + if(data instanceof ctor) { // Convert the data to be plain object to avoid pollutions data = data.toObject(false); @@ -73,10 +73,6 @@ ModelBaseClass.prototype._initProperties = function (data, options) { strict = ctor.definition.settings.strict; } - if (options.persisted !== undefined) { - this.__persisted = options.persisted === true; - } - if (ctor.hideInternalProperties) { // Object.defineProperty() is expensive. We only try to make the internal // properties hidden (non-enumerable) if the model class has the @@ -110,6 +106,13 @@ ModelBaseClass.prototype._initProperties = function (data, options) { enumerable: false, configurable: true, value: strict + }, + + __persisted: { + writable: true, + enumerable: false, + configurable: true, + value: false } }); } else { @@ -118,12 +121,23 @@ ModelBaseClass.prototype._initProperties = function (data, options) { this.__dataSource = options.dataSource; this.__strict = strict; } + + if (options.persisted !== undefined) { + this.__persisted = options.persisted === true; + } if (data.__cachedRelations) { this.__cachedRelations = data.__cachedRelations; } var keys = Object.keys(data); + + if (Array.isArray(options.fields)) { + keys = keys.filter(function(k) { + return (options.fields.indexOf(k) != -1); + }); + } + var size = keys.length; var p, propVal; for (var k = 0; k < size; k++) { @@ -169,6 +183,13 @@ ModelBaseClass.prototype._initProperties = function (data, options) { } keys = Object.keys(properties); + + if (Array.isArray(options.fields)) { + keys = keys.filter(function(k) { + return (options.fields.indexOf(k) != -1); + }); + } + size = keys.length; for (k = 0; k < size; k++) { diff --git a/test/defaults.test.js b/test/defaults.test.js index ce5be95c..0aab4ef1 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -35,4 +35,18 @@ describe('defaults', function () { done(); }); }); + + it('should ignore defaults with limited fields', function (done) { + Server.create({ host: 'localhost', port: 8080 }, function(err, s) { + should.not.exist(err); + s.port.should.equal(8080); + Server.find({ fields: ['host'] }, function (err, servers) { + servers[0].host.should.equal('localhost'); + servers[0].should.have.property('host'); + servers[0].should.not.have.property('port'); + done(); + }); + }); + }); + });