map.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. Map.prototype.OptionsConstructor = SchemaMapOptions;
  60. Map.defaultOptions = {};
  61. module.exports = Map;