diff --git a/lib/model.js b/lib/model.js index ee60ce72..ee51fa26 100644 --- a/lib/model.js +++ b/lib/model.js @@ -131,6 +131,8 @@ ModelBaseClass.prototype._initProperties = function (data, options) { self.__data[p] = propVal; } } else if (ctor.relations[p]) { + var relationType = ctor.relations[p].type; + if (!properties[p]) { var modelTo = ctor.relations[p].modelTo || ModelBaseClass; var multiple = ctor.relations[p].multiple; @@ -141,11 +143,9 @@ ModelBaseClass.prototype._initProperties = function (data, options) { } // Relation - if (ctor.relations[p].type === 'belongsTo' && propVal != null) { + if (relationType === 'belongsTo' && propVal != null) { // If the related model is populated self.__data[ctor.relations[p].keyFrom] = propVal[ctor.relations[p].keyTo]; - } else if (!self.__data[p] && propVal != null) { - self.__data[p] = propVal; } self.__cachedRelations[p] = propVal; } else { @@ -163,7 +163,6 @@ ModelBaseClass.prototype._initProperties = function (data, options) { for (k = 0; k < size; k++) { p = keys[k]; - // var prop propVal = self.__data[p]; // Set default values diff --git a/test/relations.test.js b/test/relations.test.js index 7751ee23..154f387b 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -186,6 +186,27 @@ describe('relations', function () { }); } }); + + it('should check ignore related data on creation - array', function (done) { + Book.create({ chapters: [] }, function (err, book) { + should.not.exist(err); + book.chapters.should.be.a.function; + var obj = book.toObject(); + should.not.exist(obj.chapters); + done(); + }); + }); + + it('should check ignore related data on creation - object', function (done) { + Book.create({ chapters: {} }, function (err, book) { + should.not.exist(err); + book.chapters.should.be.a.function; + var obj = book.toObject(); + should.not.exist(obj.chapters); + done(); + }); + }); + }); describe('hasMany through', function () { @@ -1898,6 +1919,31 @@ describe('relations', function () { }); }); + it('should create embedded from attributes - property name', function(done) { + var addresses = [ + {id: 'home', street: 'Home Street'}, + {id: 'work', street: 'Work Street'} + ]; + Person.create({name: 'Wilma', addresses: addresses}, function(err, p) { + should.not.exist(err); + p.addressList.at(0).id.should.equal('home'); + p.addressList.at(1).id.should.equal('work'); + done(); + }); + }); + + it('should not create embedded from attributes - relation name', function(done) { + var addresses = [ + {id: 'home', street: 'Home Street'}, + {id: 'work', street: 'Work Street'} + ]; + Person.create({name: 'Wilma', addressList: addresses}, function(err, p) { + should.not.exist(err); + p.addresses.should.have.length(0); + done(); + }); + }); + }); describe('embedsMany - relations, scope and properties', function () {