modelNamesFromRefPath.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const MongooseError = require('../../error/mongooseError');
  3. const isPathExcluded = require('../projection/isPathExcluded');
  4. const lookupLocalFields = require('./lookupLocalFields');
  5. const mpath = require('mpath');
  6. const util = require('util');
  7. const utils = require('../../utils');
  8. const hasNumericPropRE = /(\.\d+$|\.\d+\.)/g;
  9. module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, modelSchema, queryProjection) {
  10. if (refPath == null) {
  11. return [];
  12. }
  13. if (typeof refPath === 'string' && queryProjection != null && isPathExcluded(queryProjection, refPath)) {
  14. throw new MongooseError('refPath `' + refPath + '` must not be excluded in projection, got ' +
  15. util.inspect(queryProjection));
  16. }
  17. // If populated path has numerics, the end `refPath` should too. For example,
  18. // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we
  19. // should return `a.0.c` for the refPath.
  20. if (hasNumericPropRE.test(populatedPath)) {
  21. const chunks = populatedPath.split(hasNumericPropRE);
  22. if (chunks[chunks.length - 1] === '') {
  23. throw new Error('Can\'t populate individual element in an array');
  24. }
  25. let _refPath = '';
  26. let _remaining = refPath;
  27. // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]`
  28. for (let i = 0; i < chunks.length; i += 2) {
  29. const chunk = chunks[i];
  30. if (_remaining.startsWith(chunk + '.')) {
  31. _refPath += _remaining.substring(0, chunk.length) + chunks[i + 1];
  32. _remaining = _remaining.substring(chunk.length + 1);
  33. } else if (i === chunks.length - 1) {
  34. _refPath += _remaining;
  35. _remaining = '';
  36. break;
  37. } else {
  38. throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path');
  39. }
  40. }
  41. const refValue = mpath.get(_refPath, doc, lookupLocalFields);
  42. let modelNames = Array.isArray(refValue) ? refValue : [refValue];
  43. modelNames = utils.array.flatten(modelNames);
  44. return modelNames;
  45. }
  46. const refValue = mpath.get(refPath, doc, lookupLocalFields);
  47. let modelNames;
  48. if (modelSchema != null && modelSchema.virtuals.hasOwnProperty(refPath)) {
  49. modelNames = [modelSchema.virtuals[refPath].applyGetters(void 0, doc)];
  50. } else {
  51. modelNames = Array.isArray(refValue) ? refValue : [refValue];
  52. }
  53. modelNames = utils.array.flatten(modelNames);
  54. return modelNames;
  55. };