getEmbeddedDiscriminatorPath.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
  3. const get = require('../get');
  4. /*!
  5. * Like `schema.path()`, except with a document, because impossible to
  6. * determine path type without knowing the embedded discriminator key.
  7. */
  8. module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path) {
  9. const parts = path.split('.');
  10. let schematype = null;
  11. let type = 'adhocOrUndefined';
  12. filter = filter || {};
  13. update = update || {};
  14. for (let i = 0; i < parts.length; ++i) {
  15. const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.'));
  16. schematype = schema.path(subpath);
  17. if (schematype == null) {
  18. continue;
  19. }
  20. type = schema.pathType(subpath);
  21. if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) &&
  22. schematype.schema.discriminators != null) {
  23. const discriminators = schematype.schema.discriminators;
  24. const discriminatorValuePath = subpath + '.' +
  25. get(schematype, 'schema.options.discriminatorKey');
  26. const discriminatorFilterPath =
  27. discriminatorValuePath.replace(/\.\d+\./, '.');
  28. let discriminatorKey = null;
  29. if (discriminatorValuePath in filter) {
  30. discriminatorKey = filter[discriminatorValuePath];
  31. }
  32. if (discriminatorFilterPath in filter) {
  33. discriminatorKey = filter[discriminatorFilterPath];
  34. }
  35. if (discriminatorKey == null || discriminators[discriminatorKey] == null) {
  36. continue;
  37. }
  38. const rest = parts.slice(i + 1).join('.');
  39. schematype = discriminators[discriminatorKey].path(rest);
  40. if (schematype != null) {
  41. type = discriminators[discriminatorKey]._getPathType(rest);
  42. break;
  43. }
  44. }
  45. }
  46. return { type: type, schematype: schematype };
  47. };