Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validateBeforeSave.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = function(schema) {
  6. const unshift = true;
  7. schema.pre('save', false, function(next, options) {
  8. const _this = this;
  9. // Nested docs have their own presave
  10. if (this.ownerDocument) {
  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. next(error);
  33. });
  34. });
  35. } else {
  36. next();
  37. }
  38. }, null, unshift);
  39. };