All files / mongoose/lib/helpers/document cleanModifiedSubpaths.js

37.5% Statements 9/24
26.31% Branches 5/19
50% Functions 1/2
37.5% Lines 9/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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