map.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. if (init) {
  24. const map = new MongooseMap({}, this.path, doc, this.$__schemaType);
  25. if (val instanceof global.Map) {
  26. for (const key of val.keys()) {
  27. map.$init(key, map.$__schemaType.cast(val.get(key), doc, true));
  28. }
  29. } else {
  30. for (const key of Object.keys(val)) {
  31. map.$init(key, map.$__schemaType.cast(val[key], doc, true));
  32. }
  33. }
  34. return map;
  35. }
  36. return new MongooseMap(val, this.path, doc, this.$__schemaType);
  37. }
  38. clone() {
  39. const schematype = super.clone();
  40. if (this.$__schemaType != null) {
  41. schematype.$__schemaType = this.$__schemaType.clone();
  42. }
  43. return schematype;
  44. }
  45. }
  46. Map.prototype.OptionsConstructor = SchemaMapOptions;
  47. Map.defaultOptions = {};
  48. module.exports = Map;