getPath.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const numberRE = /^\d+$/;
  3. /**
  4. * Behaves like `Schema#path()`, except for it also digs into arrays without
  5. * needing to put `.0.`, so `getPath(schema, 'docArr.elProp')` works.
  6. * @api private
  7. */
  8. module.exports = function getPath(schema, path, discriminatorValueMap) {
  9. let schematype = schema.path(path);
  10. if (schematype != null) {
  11. return schematype;
  12. }
  13. const pieces = path.split('.');
  14. let cur = '';
  15. let isArray = false;
  16. for (const piece of pieces) {
  17. if (isArray && numberRE.test(piece)) {
  18. continue;
  19. }
  20. cur = cur.length === 0 ? piece : cur + '.' + piece;
  21. schematype = schema.path(cur);
  22. if (schematype?.schema) {
  23. schema = schematype.schema;
  24. if (!isArray && schematype.$isMongooseDocumentArray) {
  25. isArray = true;
  26. }
  27. if (discriminatorValueMap && discriminatorValueMap[cur]) {
  28. schema = schema.discriminators[discriminatorValueMap[cur]] ?? schema;
  29. }
  30. cur = '';
  31. } else if (schematype?.instance === 'Mixed') {
  32. // If we found a mixed path, no point in digging further, the end result is always Mixed
  33. break;
  34. }
  35. }
  36. return schematype;
  37. };