From 40f03f084b3462fe795d0fe2b8d6e8805620c981 Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Mon, 24 Nov 2014 19:20:38 +0800 Subject: [PATCH] fix recursive calls if create belongsTo model in beforeCreate hook Signed-off-by: Clark Wang --- lib/relation-definition.js | 11 ++++++++--- test/relations.test.js | 22 +++++++++++++++++++++- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 38f5552c..216a7431 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -1192,11 +1192,16 @@ BelongsTo.prototype.create = function(targetModelData, cb) { modelTo.create(targetModelData, function(err, targetModel) { if(!err) { modelInstance[fk] = targetModel[pk]; - modelInstance.save(function(err, inst) { - if (cb && err) return cb && cb(err); + if (modelInstance.isNewRecord()) { self.resetCache(targetModel); cb && cb(err, targetModel); - }); + } else { + modelInstance.save(function(err, inst) { + if (cb && err) return cb && cb(err); + self.resetCache(targetModel); + cb && cb(err, targetModel); + }); + } } else { cb && cb(err); } diff --git a/test/relations.test.js b/test/relations.test.js index 9bcbc390..4d68e2c3 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -1657,6 +1657,23 @@ describe('relations', function () { }); }); + it('should allow to create belongsTo model in beforeCreate hook', function (done) { + var mind; + Fear.beforeCreate = function (next) { + this.mind.create(function (err, m) { + mind = m; + if (err) next(err); else next(); + }); + }; + Fear.create(function (err, fear) { + should.not.exists(err); + should.exists(fear); + fear.mindId.should.be.equal(mind.id); + should.exists(fear.mind()); + done(); + }); + }); + }); describe('belongsTo with scope', function () { @@ -1680,7 +1697,10 @@ describe('relations', function () { p.personId.should.equal(person.id); person.name.should.equal('Fred'); person.passportNotes.should.equal('Some notes...'); - done(); + p.save(function (err, passport) { + should.not.exists(err); + done(); + }); }); });