map.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. const MongooseMap = require('../types/map');
  6. const SchemaMapOptions = require('../options/SchemaMapOptions');
  7. const SchemaType = require('../schematype');
  8. /*!
  9. * ignore
  10. */
  11. class Map extends SchemaType {
  12. constructor(key, options) {
  13. super(key, options, 'Map');
  14. this.$isSchemaMap = true;
  15. }
  16. set(option, value) {
  17. return SchemaType.set(option, value);
  18. }
  19. cast(val, doc, init) {
  20. if (val instanceof MongooseMap) {
  21. return val;
  22. }
  23. const path = this.path;
  24. if (init) {
  25. const map = new MongooseMap({}, path, doc, this.$__schemaType);
  26. if (val instanceof global.Map) {
  27. for (const key of val.keys()) {
  28. let _val = val.get(key);
  29. if (_val == null) {
  30. _val = map.$__schemaType._castNullish(_val);
  31. } else {
  32. _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key });
  33. }
  34. map.$init(key, _val);
  35. }
  36. } else {
  37. for (const key of Object.keys(val)) {
  38. let _val = val[key];
  39. if (_val == null) {
  40. _val = map.$__schemaType._castNullish(_val);
  41. } else {
  42. _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key });
  43. }
  44. map.$init(key, _val);
  45. }
  46. }
  47. return map;
  48. }
  49. return new MongooseMap(val, path, doc, this.$__schemaType);
  50. }
  51. clone() {
  52. const schematype = super.clone();
  53. if (this.$__schemaType != null) {
  54. schematype.$__schemaType = this.$__schemaType.clone();
  55. }
  56. return schematype;
  57. }
  58. }
  59. /**
  60. * This schema type's name, to defend against minifiers that mangle
  61. * function names.
  62. *
  63. * @api public
  64. */
  65. Map.schemaName = 'Map';
  66. Map.prototype.OptionsConstructor = SchemaMapOptions;
  67. Map.defaultOptions = {};
  68. module.exports = Map;