fix embedsOne error when embed instance is undefined or null

Signed-off-by: Clark Wang <clark.wangs@gmail.com>
This commit is contained in:
Clark Wang 2014-11-28 13:45:47 +08:00
parent d5dcf0a966
commit 9d2e6516c3
2 changed files with 21 additions and 2 deletions

View File

@ -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;

View File

@ -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();