validation.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*!
  2. * Module requirements
  3. */
  4. var MongooseError = require('../error.js');
  5. /**
  6. * Document Validation Error
  7. *
  8. * @api private
  9. * @param {Document} instance
  10. * @inherits MongooseError
  11. */
  12. function ValidationError(instance) {
  13. this.errors = {};
  14. if (instance && instance.constructor.name === 'model') {
  15. MongooseError.call(this, instance.constructor.modelName + ' validation failed');
  16. } else {
  17. MongooseError.call(this, 'Validation failed');
  18. }
  19. if (Error.captureStackTrace) {
  20. Error.captureStackTrace(this);
  21. } else {
  22. this.stack = new Error().stack;
  23. }
  24. this.name = 'ValidationError';
  25. if (instance) {
  26. instance.errors = this.errors;
  27. }
  28. }
  29. /*!
  30. * Inherits from MongooseError.
  31. */
  32. ValidationError.prototype = Object.create(MongooseError.prototype);
  33. ValidationError.prototype.constructor = MongooseError;
  34. /**
  35. * Console.log helper
  36. */
  37. ValidationError.prototype.toString = function() {
  38. var ret = this.name + ': ';
  39. var msgs = [];
  40. Object.keys(this.errors || {}).forEach(function(key) {
  41. if (this === this.errors[key]) {
  42. return;
  43. }
  44. msgs.push(String(this.errors[key]));
  45. }, this);
  46. return ret + msgs.join(', ');
  47. };
  48. /*!
  49. * Module exports
  50. */
  51. module.exports = exports = ValidationError;