cleanModifiedSubpaths.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = function cleanModifiedSubpaths(doc, path, options) {
  6. options = options || {};
  7. const skipDocArrays = options.skipDocArrays;
  8. let deleted = 0;
  9. if (!doc) {
  10. return deleted;
  11. }
  12. for (const modifiedPath of Object.keys(doc.$__.activePaths.getStatePaths('modify'))) {
  13. if (skipDocArrays) {
  14. const schemaType = doc.$__schema.path(modifiedPath);
  15. if (schemaType?.$isMongooseDocumentArray) {
  16. continue;
  17. }
  18. }
  19. if (modifiedPath.startsWith(path + '.')) {
  20. doc.$__.activePaths.clearPath(modifiedPath);
  21. ++deleted;
  22. if (doc.$isSubdocument) {
  23. cleanParent(doc, modifiedPath);
  24. }
  25. }
  26. }
  27. return deleted;
  28. };
  29. function cleanParent(doc, path, seen = new Set()) {
  30. if (seen.has(doc)) {
  31. throw new Error('Infinite subdocument loop: subdoc with _id ' + doc._id + ' is a parent of itself');
  32. }
  33. const parent = doc.$parent();
  34. const newPath = doc.$__pathRelativeToParent(void 0, false) + '.' + path;
  35. parent.$__.activePaths.clearPath(newPath);
  36. if (parent.$isSubdocument) {
  37. cleanParent(parent, newPath, seen);
  38. }
  39. }