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:
parent
efe4601fdb
commit
ce2b580ccd
|
@ -316,7 +316,7 @@ DataAccessObject.updateOrCreate = DataAccessObject.upsert = function upsert(data
|
||||||
* @param {Object} query Search conditions. See [find](#dataaccessobjectfindquery-callback) for query format.
|
* @param {Object} query Search conditions. See [find](#dataaccessobjectfindquery-callback) for query format.
|
||||||
* For example: `{where: {test: 'me'}}`.
|
* For example: `{where: {test: 'me'}}`.
|
||||||
* @param {Object} data Object to create.
|
* @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) {
|
DataAccessObject.findOrCreate = function findOrCreate(query, data, callback) {
|
||||||
if (query === undefined) {
|
if (query === undefined) {
|
||||||
|
@ -334,8 +334,10 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, callback) {
|
||||||
var t = this;
|
var t = this;
|
||||||
this.findOne(query, function (err, record) {
|
this.findOne(query, function (err, record) {
|
||||||
if (err) return callback(err);
|
if (err) return callback(err);
|
||||||
if (record) return callback(null, record);
|
if (record) return callback(null, record, false);
|
||||||
t.create(data, callback);
|
t.create(data, function (err, record) {
|
||||||
|
callback(err, record, record != null);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -1122,12 +1122,14 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
it('should find or create', function (test) {
|
it('should find or create', function (test) {
|
||||||
var email = 'some email ' + Math.random();
|
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);
|
||||||
test.ok(!u.age);
|
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.equals(u.id.toString(), u2.id.toString(), 'Same user ids');
|
||||||
test.ok(!u2.age);
|
test.ok(!u2.age);
|
||||||
|
test.ok(!created);
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in New Issue