add a flag to callback of findOrCreate to indicate find or create

Signed-off-by: Clark Wang <clark.wangs@gmail.com>
This commit is contained in:
Clark Wang 2014-12-25 22:19:15 +08:00
parent efe4601fdb
commit ce2b580ccd
2 changed files with 9 additions and 5 deletions

View File

@ -316,7 +316,7 @@ DataAccessObject.updateOrCreate = DataAccessObject.upsert = function upsert(data
* @param {Object} query Search conditions. See [find](#dataaccessobjectfindquery-callback) for query format.
* For example: `{where: {test: 'me'}}`.
* @param {Object} data Object to create.
* @param {Function} cb Callback called with (err, instance)
* @param {Function} cb Callback called with (err, instance, created)
*/
DataAccessObject.findOrCreate = function findOrCreate(query, data, callback) {
if (query === undefined) {
@ -334,8 +334,10 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, callback) {
var t = this;
this.findOne(query, function (err, record) {
if (err) return callback(err);
if (record) return callback(null, record);
t.create(data, callback);
if (record) return callback(null, record, false);
t.create(data, function (err, record) {
callback(err, record, record != null);
});
});
};

View File

@ -1122,12 +1122,14 @@ function testOrm(dataSource) {
it('should find or create', function (test) {
var email = 'some email ' + Math.random();
User.findOrCreate({where: {email: email}}, function (err, u) {
User.findOrCreate({where: {email: email}}, function (err, u, created) {
test.ok(u);
test.ok(!u.age);
User.findOrCreate({where: {email: email}}, {age: 21}, function (err, u2) {
test.ok(created);
User.findOrCreate({where: {email: email}}, {age: 21}, function (err, u2, created) {
test.equals(u.id.toString(), u2.id.toString(), 'Same user ids');
test.ok(!u2.age);
test.ok(!created);
test.done();
});
});