mixed.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const SchemaType = require('../schematype');
  6. const symbols = require('./symbols');
  7. const utils = require('../utils');
  8. /**
  9. * Mixed SchemaType constructor.
  10. *
  11. * @param {String} path
  12. * @param {Object} options
  13. * @inherits SchemaType
  14. * @api public
  15. */
  16. function Mixed(path, options) {
  17. if (options && options.default) {
  18. const def = options.default;
  19. if (Array.isArray(def) && def.length === 0) {
  20. // make sure empty array defaults are handled
  21. options.default = Array;
  22. } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) {
  23. // prevent odd "shared" objects between documents
  24. options.default = function() {
  25. return {};
  26. };
  27. }
  28. }
  29. SchemaType.call(this, path, options, 'Mixed');
  30. this[symbols.schemaMixedSymbol] = true;
  31. }
  32. /**
  33. * This schema type's name, to defend against minifiers that mangle
  34. * function names.
  35. *
  36. * @api public
  37. */
  38. Mixed.schemaName = 'Mixed';
  39. /*!
  40. * Inherits from SchemaType.
  41. */
  42. Mixed.prototype = Object.create(SchemaType.prototype);
  43. Mixed.prototype.constructor = Mixed;
  44. /**
  45. * Attaches a getter for all Mixed paths.
  46. *
  47. * ####Example:
  48. *
  49. * // Hide the 'hidden' path
  50. * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null }));
  51. *
  52. * const Model = mongoose.model('Test', new Schema({ test: {} }));
  53. * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null
  54. *
  55. * @param {Function} getter
  56. * @return {this}
  57. * @function get
  58. * @static
  59. * @api public
  60. */
  61. Mixed.get = SchemaType.get;
  62. /**
  63. * Casts `val` for Mixed.
  64. *
  65. * _this is a no-op_
  66. *
  67. * @param {Object} value to cast
  68. * @api private
  69. */
  70. Mixed.prototype.cast = function(val) {
  71. return val;
  72. };
  73. /**
  74. * Casts contents for queries.
  75. *
  76. * @param {String} $cond
  77. * @param {any} [val]
  78. * @api private
  79. */
  80. Mixed.prototype.castForQuery = function($cond, val) {
  81. if (arguments.length === 2) {
  82. return val;
  83. }
  84. return $cond;
  85. };
  86. /*!
  87. * Module exports.
  88. */
  89. module.exports = Mixed;