Skip to content

Commit

Permalink
feat(document): add hooks for updateOne()
Browse files Browse the repository at this point in the history
Fix #7133
  • Loading branch information
vkarpov15 committed Nov 17, 2018
1 parent f7afe78 commit 774508a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
14 changes: 10 additions & 4 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -592,10 +592,16 @@ Document.prototype.update = function update() {
* @instance
*/

Document.prototype.updateOne = function updateOne() {
const args = utils.args(arguments);
args.unshift({_id: this._id});
return this.constructor.updateOne.apply(this.constructor, args);
Document.prototype.updateOne = function updateOne(doc, options, callback) {
return utils.promiseOrCallback(callback, cb => this.$__updateOne(doc, options, cb));
};

/*!
* ignore
*/

Document.prototype.$__updateOne = function $__updateOne(doc, options, callback) {
return this.constructor.updateOne({ _id: this._id }, doc, options, callback);
};

/**
Expand Down
12 changes: 9 additions & 3 deletions lib/helpers/model/applyHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ applyHooks.middlewareFunctions = [
'save',
'validate',
'remove',
'updateOne',
'init'
];

Expand Down Expand Up @@ -58,10 +59,13 @@ function applyHooks(model, schema, options) {
// information.

const middleware = schema.s.hooks.filter(hook => {
if (hook.name !== 'remove') {
return true;
if (hook.name === 'updateOne') {
return !!hook['document'];
}
return hook['document'] == null || !!hook['document'];
if (hook.name === 'remove') {
return hook['document'] == null || !!hook['document'];
}
return true;
});

objToDecorate.$__save = middleware.
Expand All @@ -70,6 +74,8 @@ function applyHooks(model, schema, options) {
createWrapper('validate', objToDecorate.$__validate, null, kareemOptions);
objToDecorate.$__remove = middleware.
createWrapper('remove', objToDecorate.$__remove, null, kareemOptions);
objToDecorate.$__updateOne = middleware.
createWrapper('updateOne', objToDecorate.$__updateOne, null, kareemOptions);
objToDecorate.$__init = middleware.
createWrapperSync('init', objToDecorate.$__init, null, kareemOptions);

Expand Down
9 changes: 6 additions & 3 deletions lib/helpers/query/applyQueryMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,13 @@ function applyQueryMiddleware(Query, model) {
};

const middleware = model.hooks.filter(hook => {
if (hook.name !== 'remove') {
return true;
if (hook.name === 'updateOne') {
return hook.query == null || !!hook.query;
}
return !!hook.query;
if (hook.name === 'remove') {
return !!hook.query;
}
return true;
});

// `update()` thunk has a different name because `_update` was already taken
Expand Down

0 comments on commit 774508a

Please sign in to comment.