validateBeforeSave.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = function(schema) {
  6. const unshift = true;
  7. schema.pre('save', false, function validateBeforeSave(next, options) {
  8. const _this = this;
  9. // Nested docs have their own presave
  10. if (this.$isSubdocument) {
  11. return next();
  12. }
  13. const hasValidateBeforeSaveOption = options &&
  14. (typeof options === 'object') &&
  15. ('validateBeforeSave' in options);
  16. let shouldValidate;
  17. if (hasValidateBeforeSaveOption) {
  18. shouldValidate = !!options.validateBeforeSave;
  19. } else {
  20. shouldValidate = this.$__schema.options.validateBeforeSave;
  21. }
  22. // Validate
  23. if (shouldValidate) {
  24. const hasValidateModifiedOnlyOption = options &&
  25. (typeof options === 'object') &&
  26. ('validateModifiedOnly' in options);
  27. const validateOptions = hasValidateModifiedOnlyOption ?
  28. { validateModifiedOnly: options.validateModifiedOnly } :
  29. null;
  30. this.$validate(validateOptions, function(error) {
  31. return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
  32. _this.$op = 'save';
  33. next(error);
  34. });
  35. });
  36. } else {
  37. next();
  38. }
  39. }, null, unshift);
  40. };