discriminator.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. 'use strict';
  2. const defineKey = require('../document/compile').defineKey;
  3. const get = require('../get');
  4. const utils = require('../../utils');
  5. const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = {
  6. toJSON: true,
  7. toObject: true,
  8. _id: true,
  9. id: true
  10. };
  11. /*!
  12. * ignore
  13. */
  14. module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) {
  15. if (!(schema && schema.instanceOfSchema)) {
  16. throw new Error('You must pass a valid discriminator Schema');
  17. }
  18. if (model.schema.discriminatorMapping &&
  19. !model.schema.discriminatorMapping.isRoot) {
  20. throw new Error('Discriminator "' + name +
  21. '" can only be a discriminator of the root model');
  22. }
  23. if (applyPlugins) {
  24. const applyPluginsToDiscriminators = get(model.base,
  25. 'options.applyPluginsToDiscriminators', false);
  26. // Even if `applyPluginsToDiscriminators` isn't set, we should still apply
  27. // global plugins to schemas embedded in the discriminator schema (gh-7370)
  28. model.base._applyPlugins(schema, {
  29. skipTopLevel: !applyPluginsToDiscriminators
  30. });
  31. }
  32. const key = model.schema.options.discriminatorKey;
  33. const baseSchemaAddition = {};
  34. baseSchemaAddition[key] = {
  35. default: void 0,
  36. select: true,
  37. $skipDiscriminatorCheck: true
  38. };
  39. baseSchemaAddition[key][model.schema.options.typeKey] = String;
  40. model.schema.add(baseSchemaAddition);
  41. defineKey(key, null, model.prototype, null, [key], model.schema.options);
  42. if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) {
  43. throw new Error('Discriminator "' + name +
  44. '" cannot have field with name "' + key + '"');
  45. }
  46. let value = name;
  47. if (typeof tiedValue == 'string' && tiedValue.length) {
  48. value = tiedValue;
  49. }
  50. function merge(schema, baseSchema) {
  51. // Retain original schema before merging base schema
  52. schema._originalSchema = schema.clone();
  53. if (baseSchema.paths._id &&
  54. baseSchema.paths._id.options &&
  55. !baseSchema.paths._id.options.auto) {
  56. const originalSchema = schema;
  57. utils.merge(schema, originalSchema);
  58. delete schema.paths._id;
  59. delete schema.tree._id;
  60. }
  61. // Find conflicting paths: if something is a path in the base schema
  62. // and a nested path in the child schema, overwrite the base schema path.
  63. // See gh-6076
  64. const baseSchemaPaths = Object.keys(baseSchema.paths);
  65. const conflictingPaths = [];
  66. for (let i = 0; i < baseSchemaPaths.length; ++i) {
  67. if (schema.nested[baseSchemaPaths[i]]) {
  68. conflictingPaths.push(baseSchemaPaths[i]);
  69. }
  70. }
  71. utils.merge(schema, baseSchema, {
  72. omit: { discriminators: true },
  73. omitNested: conflictingPaths.reduce((cur, path) => {
  74. cur['tree.' + path] = true;
  75. return cur;
  76. }, {})
  77. });
  78. // Clean up conflicting paths _after_ merging re: gh-6076
  79. for (let i = 0; i < conflictingPaths.length; ++i) {
  80. delete schema.paths[conflictingPaths[i]];
  81. }
  82. const obj = {};
  83. obj[key] = {
  84. default: value,
  85. select: true,
  86. set: function(newName) {
  87. if (newName === value) {
  88. return value;
  89. }
  90. throw new Error('Can\'t set discriminator key "' + key + '"');
  91. },
  92. $skipDiscriminatorCheck: true
  93. };
  94. obj[key][schema.options.typeKey] = String;
  95. schema.add(obj);
  96. schema.discriminatorMapping = {key: key, value: value, isRoot: false};
  97. if (baseSchema.options.collection) {
  98. schema.options.collection = baseSchema.options.collection;
  99. }
  100. const toJSON = schema.options.toJSON;
  101. const toObject = schema.options.toObject;
  102. const _id = schema.options._id;
  103. const id = schema.options.id;
  104. const keys = Object.keys(schema.options);
  105. schema.options.discriminatorKey = baseSchema.options.discriminatorKey;
  106. for (let i = 0; i < keys.length; ++i) {
  107. const _key = keys[i];
  108. if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) {
  109. if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) {
  110. throw new Error('Can\'t customize discriminator option ' + _key +
  111. ' (can only modify ' +
  112. Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') +
  113. ')');
  114. }
  115. }
  116. }
  117. schema.options = utils.clone(baseSchema.options);
  118. if (toJSON) schema.options.toJSON = toJSON;
  119. if (toObject) schema.options.toObject = toObject;
  120. if (typeof _id !== 'undefined') {
  121. schema.options._id = _id;
  122. }
  123. schema.options.id = id;
  124. schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks);
  125. schema.plugins = Array.prototype.slice(baseSchema.plugins);
  126. schema.callQueue = baseSchema.callQueue.concat(schema.callQueue);
  127. delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema
  128. }
  129. // merges base schema into new discriminator schema and sets new type field.
  130. merge(schema, model.schema);
  131. if (!model.discriminators) {
  132. model.discriminators = {};
  133. }
  134. if (!model.schema.discriminatorMapping) {
  135. model.schema.discriminatorMapping = {key: key, value: null, isRoot: true};
  136. }
  137. if (!model.schema.discriminators) {
  138. model.schema.discriminators = {};
  139. }
  140. model.schema.discriminators[name] = schema;
  141. if (model.discriminators[name]) {
  142. throw new Error('Discriminator with name "' + name + '" already exists');
  143. }
  144. return schema;
  145. };