saveSubdocs.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const each = require('../helpers/each');
  3. /*!
  4. * ignore
  5. */
  6. module.exports = function(schema) {
  7. const unshift = true;
  8. schema.s.hooks.pre('save', false, function(next) {
  9. if (this.$isSubdocument) {
  10. next();
  11. return;
  12. }
  13. const _this = this;
  14. const subdocs = this.$getAllSubdocs();
  15. if (!subdocs.length) {
  16. next();
  17. return;
  18. }
  19. each(subdocs, function(subdoc, cb) {
  20. subdoc.$__schema.s.hooks.execPre('save', subdoc, function(err) {
  21. cb(err);
  22. });
  23. }, function(error) {
  24. if (error) {
  25. return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
  26. next(error);
  27. });
  28. }
  29. next();
  30. });
  31. }, null, unshift);
  32. schema.s.hooks.post('save', function(doc, next) {
  33. if (this.$isSubdocument) {
  34. next();
  35. return;
  36. }
  37. const _this = this;
  38. const subdocs = this.$getAllSubdocs();
  39. if (!subdocs.length) {
  40. next();
  41. return;
  42. }
  43. each(subdocs, function(subdoc, cb) {
  44. subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) {
  45. cb(err);
  46. });
  47. }, function(error) {
  48. if (error) {
  49. return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
  50. next(error);
  51. });
  52. }
  53. next();
  54. });
  55. }, null, unshift);
  56. };