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 <clark.wangs@gmail.com>
This commit is contained in:
Clark Wang 2015-02-04 14:54:28 +08:00
parent 9b675ef3dc
commit 09f7c92cbe
1 changed files with 11 additions and 16 deletions

View File

@ -1539,22 +1539,17 @@ 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));
}
});
};