selectPopulatedFields.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = function selectPopulatedFields(query) {
  6. const opts = query._mongooseOptions;
  7. if (opts.populate != null) {
  8. const paths = Object.keys(opts.populate);
  9. const userProvidedFields = query._userProvidedFields || {};
  10. if (query.selectedInclusively()) {
  11. for (let i = 0; i < paths.length; ++i) {
  12. if (!isPathInFields(userProvidedFields, paths[i])) {
  13. query.select(paths[i]);
  14. } else if (userProvidedFields[paths[i]] === 0) {
  15. delete query._fields[paths[i]];
  16. }
  17. }
  18. } else if (query.selectedExclusively()) {
  19. for (let i = 0; i < paths.length; ++i) {
  20. if (userProvidedFields[paths[i]] == null) {
  21. delete query._fields[paths[i]];
  22. }
  23. }
  24. }
  25. }
  26. };
  27. /*!
  28. * ignore
  29. */
  30. function isPathInFields(userProvidedFields, path) {
  31. const pieces = path.split('.');
  32. const len = pieces.length;
  33. let cur = pieces[0];
  34. for (let i = 1; i < len; ++i) {
  35. if (userProvidedFields[cur] != null) {
  36. return true;
  37. }
  38. cur += '.' + pieces[i];
  39. }
  40. return userProvidedFields[cur] != null;
  41. }