From 09f7c92cbeafab9e934a3e81b178936f568a4cf0 Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Wed, 4 Feb 2015 14:54:28 +0800 Subject: [PATCH] use findOrCreate in hasOne#create So hasOne#create could take advantage from optimized findOrCreate, which can avoid multiple creation among concurrent requests. Signed-off-by: Clark Wang --- lib/relation-definition.js | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 40584393..77db69e0 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -1538,23 +1538,18 @@ HasOne.prototype.create = function (targetModelData, cb) { this.definition.applyScope(modelInstance, query); this.definition.applyProperties(modelInstance, targetModelData); - - modelTo.findOne(query, function(err, result) { - if(err) { - cb(err); - } else if(result) { - cb(new Error('HasOne relation cannot create more than one instance of ' - + modelTo.modelName)); + + modelTo.findOrCreate(query, targetModelData, function (err, targetModel, created) { + if (err) { + return cb && cb(err); + } + if (created) { + // Refresh the cache + self.resetCache(targetModel); + cb && cb(err, targetModel); } else { - modelTo.create(targetModelData, function (err, targetModel) { - if (!err) { - // Refresh the cache - self.resetCache(targetModel); - cb && cb(err, targetModel); - } else { - cb && cb(err); - } - }); + cb && cb(new Error('HasOne relation cannot create more than one instance of ' + + modelTo.modelName)); } }); };