saveSubdocs.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = function saveSubdocs(schema) {
  6. const unshift = true;
  7. schema.s.hooks.pre('save', false, async function saveSubdocsPreSave() {
  8. if (this.$isSubdocument) {
  9. return;
  10. }
  11. const subdocs = this.$getAllSubdocs({ useCache: true });
  12. if (!subdocs.length) {
  13. return;
  14. }
  15. const options = this.$__.saveOptions;
  16. await Promise.all(subdocs.map(subdoc => subdoc._execDocumentPreHooks('save', options)));
  17. // Invalidate subdocs cache because subdoc pre hooks can add new subdocuments
  18. if (this.$__.saveOptions) {
  19. this.$__.saveOptions.__subdocs = null;
  20. }
  21. }, null, unshift);
  22. schema.s.hooks.pre('save', async function saveSubdocsPreDeleteOne() {
  23. const removedSubdocs = this.$__.removedSubdocs;
  24. if (!removedSubdocs?.length) {
  25. return;
  26. }
  27. const promises = [];
  28. for (const subdoc of removedSubdocs) {
  29. promises.push(subdoc._execDocumentPreHooks('deleteOne'));
  30. }
  31. await Promise.all(promises);
  32. });
  33. schema.s.hooks.post('save', async function saveSubdocsPostDeleteOne() {
  34. const removedSubdocs = this.$__.removedSubdocs;
  35. if (!removedSubdocs?.length) {
  36. return;
  37. }
  38. const promises = [];
  39. for (const subdoc of removedSubdocs) {
  40. promises.push(subdoc._execDocumentPostHooks('deleteOne'));
  41. }
  42. this.$__.removedSubdocs = null;
  43. await Promise.all(promises);
  44. });
  45. schema.s.hooks.post('save', async function saveSubdocsPostSave() {
  46. if (this.$isSubdocument) {
  47. return;
  48. }
  49. const subdocs = this.$getAllSubdocs({ useCache: true });
  50. if (!subdocs.length) {
  51. return;
  52. }
  53. const promises = [];
  54. for (const subdoc of subdocs) {
  55. promises.push(subdoc._execDocumentPostHooks('save'));
  56. }
  57. await Promise.all(promises);
  58. }, null, unshift);
  59. };