Skip to content

Commit

Permalink
Merge pull request #462 from bahung1221/master
Browse files Browse the repository at this point in the history
#461 Call 'find' and then 'update/create' instead call 'updateOrCreat…
  • Loading branch information
1602 committed May 8, 2019
2 parents 0f79634 + 71c0e64 commit be76ced
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 31 deletions.
42 changes: 11 additions & 31 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -327,43 +327,23 @@ function connection(schema) {
* Update or insert
*/
AbstractClass.upsert = AbstractClass.updateOrCreate = function upsert(data, callback) {

const Model = this;
if (!data.id) {
return this.create(data, callback);
}

if (this.schema.adapter.updateOrCreate) {
const inst = new Model(data);
this.schema.callAdapter('updateOrCreate', Model.modelName, stripUndefined(inst.toObject(true)), (err, data) => {
if (data) {
return inst.reload(callback);
}
callback(err, null);
});
} else {
this.find(data.id, (err, inst) => {
if (err) {
return callback(err);
}

if (inst) {
inst.updateAttributes(data, callback);
} else {
const obj = new Model(data);
obj.save(data, callback);
}
});
}
this.find(data.id, (err, inst) => {
if (err) {
return callback(err);
}

function stripUndefined(data) {
return Object.keys(data)
.filter(key => typeof data[key] !== 'undefined')
.reduce((result, key) => {
result[key] = data[key];
return result;
}, {});
}
if (inst) {
inst.updateAttributes(data, callback);
} else {
const obj = new Model(data);
obj.save(data, callback);
}
});
};

/**
Expand Down
15 changes: 15 additions & 0 deletions test/hooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ describe('hooks', function() {
(new User).save();
});

it('should be triggered on upsert', function(done) {
addHooks('Create', done);
User.upsert({ name: 'Anatoliy' });
});

it('afterCreate should not be triggered on failed create', function(done) {
const old = User.schema.adapter.create;
User.schema.adapter.create = function(modelName, id, cb) {
Expand Down Expand Up @@ -127,6 +132,11 @@ describe('hooks', function() {
});
});

it('should be triggered on upsert', function(done) {
addHooks('Save', done);
User.upsert();
});

it('should be triggered on save', function(done) {
User.create(function(err, user) {
addHooks('Save', done);
Expand Down Expand Up @@ -218,6 +228,11 @@ describe('hooks', function() {
});
});

it('should be triggered on upsert', function(done) {
addHooks('Update', done);
User.upsert({ id: 1 });
});

it('should be triggered on save', function(done) {
User.create(function(err, user) {
addHooks('Update', done);
Expand Down

0 comments on commit be76ced

Please sign in to comment.