selectPopulatedFields.js 1.2 KB

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