From 9d2e6516c3fba8c0f1b152a6925ef2f9445c715a Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Fri, 28 Nov 2014 13:45:47 +0800 Subject: [PATCH] fix embedsOne error when embed instance is undefined or null Signed-off-by: Clark Wang --- lib/relation-definition.js | 7 +++++-- test/relations.test.js | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 38f5552c..a939613e 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -1751,7 +1751,7 @@ RelationDefinition.embedsOne = function (modelFrom, modelTo, params) { configurable: true, get: function() { var relation = new EmbedsOne(definition, this); - var relationMethod = relation.related.bind(relation) + var relationMethod = relation.related.bind(relation); relationMethod.create = relation.create.bind(relation); relationMethod.build = relation.build.bind(relation); relationMethod.update = relation.update.bind(relation); @@ -1795,7 +1795,10 @@ EmbedsOne.prototype.related = function (refresh, params) { } var embeddedInstance = modelInstance[propertyName]; - embeddedInstance.__persisted = true; + + if (embeddedInstance) { + embeddedInstance.__persisted = true; + } if (typeof params === 'function') { // acts as async getter var cb = params; diff --git a/test/relations.test.js b/test/relations.test.js index 9bcbc390..83186378 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -2011,6 +2011,7 @@ describe('relations', function () { describe('embedsOne', function () { var person; + var Passport; var Other; before(function () { @@ -2021,6 +2022,7 @@ describe('relations', function () { {name:{type:'string', required: true}}, {idInjection: false} ); + Address = tmp.define('Address', { street: String }, { idInjection: false }); Other = db.define('Other', {name: String}); }); @@ -2028,6 +2030,7 @@ describe('relations', function () { Person.embedsOne(Passport, { default: {name: 'Anonymous'} // a bit contrived }); + Person.embedsOne(Address); // all by default db.automigrate(done); }); @@ -2039,6 +2042,19 @@ describe('relations', function () { p.passportItem.build.should.be.a.function; p.passportItem.destroy.should.be.a.function; }); + + it('should behave properly without default or being set', function (done) { + var p = new Person(); + should.not.exist(p.address); + var a = p.addressItem(); + should.not.exist(a); + Person.create({}, function (err, p) { + should.not.exist(p.address); + var a = p.addressItem(); + should.not.exist(a); + done(); + }); + }); it('should return an instance with default values', function() { var p = new Person();