Merge pull request #423 from clarkorz/hasOne-findOrCreate

use findOrCreate in hasOne#create
This commit is contained in:
Raymond Feng 2015-02-11 20:51:33 -08:00
commit cc1791b01d
1 changed files with 11 additions and 16 deletions

View File

@ -1538,23 +1538,18 @@ HasOne.prototype.create = function (targetModelData, cb) {
this.definition.applyScope(modelInstance, query); this.definition.applyScope(modelInstance, query);
this.definition.applyProperties(modelInstance, targetModelData); this.definition.applyProperties(modelInstance, targetModelData);
modelTo.findOne(query, function(err, result) { modelTo.findOrCreate(query, targetModelData, function (err, targetModel, created) {
if(err) { if (err) {
cb(err); return cb && cb(err);
} else if(result) { }
cb(new Error('HasOne relation cannot create more than one instance of ' if (created) {
+ modelTo.modelName)); // Refresh the cache
self.resetCache(targetModel);
cb && cb(err, targetModel);
} else { } else {
modelTo.create(targetModelData, function (err, targetModel) { cb && cb(new Error('HasOne relation cannot create more than one instance of '
if (!err) { + modelTo.modelName));
// Refresh the cache
self.resetCache(targetModel);
cb && cb(err, targetModel);
} else {
cb && cb(err);
}
});
} }
}); });
}; };