Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: improve error handling and refactor to use async/await
  • Loading branch information
vkarpov15 committed Jul 7, 2024
commit 5f55a30197c403a2b720337733356dbedd170c82
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