Skip to content

Commit

Permalink
fix: improve error handling and refactor to use async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jul 7, 2024
1 parent 3c0cb46 commit 5f55a30
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
29 changes: 15 additions & 14 deletions lib/plugins/saveSubdocs.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,25 +36,26 @@ module.exports = function saveSubdocs(schema) {
});
}, null, unshift);

schema.s.hooks.post('save', function saveSubdocsPostDeleteOne(doc, next) {
schema.s.hooks.post('save', async function saveSubdocsPostDeleteOne() {
const removedSubdocs = this.$__.removedSubdocs;
if (!removedSubdocs || !removedSubdocs.length) {
return next();
return;
}

each(removedSubdocs, function(subdoc, cb) {
subdoc.$__schema.s.hooks.execPost('deleteOne', subdoc, [subdoc], function(err) {
cb(err);
});
}, (error) => {
this.$__.removedSubdocs = null;
if (error) {
return this.$__schema.s.hooks.execPost('deleteOne:error', this, [this], { error: error }, function(error) {
next(error);
const promises = [];
for (const subdoc of removedSubdocs) {
promises.push(new Promise((resolve, reject) => {
subdoc.$__schema.s.hooks.execPost('deleteOne', subdoc, [subdoc], function(err) {
if (err) {
return reject(err);
}
resolve();
});
}
next();
});
}));
}

this.$__.removedSubdocs = null;
await Promise.all(promises);
});

schema.s.hooks.post('save', function saveSubdocsPostSave(doc, next) {
Expand Down
11 changes: 10 additions & 1 deletion test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13544,6 +13544,7 @@ describe('document', function() {
preDeleteOne: 0,
postDeleteOne: 0
};
let postDeleteOneError = null;
ChildSchema.pre('save', function(next) {
++called.preSave;
next();
Expand All @@ -13558,7 +13559,7 @@ describe('document', function() {
});
ChildSchema.post('deleteOne', { document: true, query: false }, function(subdoc, next) {
++called.postDeleteOne;
next();
next(postDeleteOneError);
});
const ParentSchema = new Schema({ name: String, children: [ChildSchema] });
const ParentModel = db.model('Parent', ParentSchema);
Expand Down Expand Up @@ -13590,6 +13591,14 @@ describe('document', function() {
preDeleteOne: 1,
postDeleteOne: 1
});

postDeleteOneError = new Error('Test error in post deleteOne hook');
const child3 = doc.children[1];
child3.deleteOne();
await assert.rejects(
() => doc.save(),
/Test error in post deleteOne hook/
);
});
});

Expand Down

0 comments on commit 5f55a30

Please sign in to comment.