markArraySubdocsPopulated.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const utils = require('../../utils');
  3. /*!
  4. * If populating a path within a document array, make sure each
  5. * subdoc within the array knows its subpaths are populated.
  6. *
  7. * ####Example:
  8. * const doc = await Article.findOne().populate('comments.author');
  9. * doc.comments[0].populated('author'); // Should be set
  10. */
  11. module.exports = function markArraySubdocsPopulated(doc, populated) {
  12. if (doc._id == null || populated == null || populated.length === 0) {
  13. return;
  14. }
  15. const id = String(doc._id);
  16. for (const item of populated) {
  17. if (item.isVirtual) {
  18. continue;
  19. }
  20. const path = item.path;
  21. const pieces = path.split('.');
  22. for (let i = 0; i < pieces.length - 1; ++i) {
  23. const subpath = pieces.slice(0, i + 1).join('.');
  24. const rest = pieces.slice(i + 1).join('.');
  25. const val = doc.get(subpath);
  26. if (val == null) {
  27. continue;
  28. }
  29. if (utils.isMongooseDocumentArray(val)) {
  30. for (let j = 0; j < val.length; ++j) {
  31. val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
  32. }
  33. break;
  34. }
  35. }
  36. }
  37. };