From ce2b580ccde6e43f45a4a050e926603fd48f602f Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Thu, 25 Dec 2014 22:19:15 +0800 Subject: [PATCH] add a flag to callback of findOrCreate to indicate find or create Signed-off-by: Clark Wang --- lib/dao.js | 8 +++++--- test/common_test.js | 6 ++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/dao.js b/lib/dao.js index b7a35021..f800d79c 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -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); + }); }); }; diff --git a/test/common_test.js b/test/common_test.js index 2f91b5a7..0b251e59 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -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(); }); });