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

5.26% Statements 1/19
0% Branches 0/12
0% Functions 0/1
5.55% Lines 1/18

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                          1x                                                  
'use strict';
 
/**
 * Find the deepest subdocument along a given path to ensure setter functions run
 * with the correct subdocument as `this`. If no subdocuments, returns the top-level
 * document.
 *
 * @param {Document} doc
 * @param {String[]} parts
 * @param {Schema} schema
 * @returns Document
 */
 
module.exports = function getDeepestSubdocumentForPath(doc, parts, schema) {
  let curPath = parts[0];
  let curSchema = schema;
  let subdoc = doc;
  for (let i = 0; i < parts.length - 1; ++i) {
    const curSchemaType = curSchema.path(curPath);
    if (curSchemaType && curSchemaType.schema) {
      let newSubdoc = subdoc.get(curPath);
      curSchema = curSchemaType.schema;
      curPath = parts[i + 1];
      if (Array.isArray(newSubdoc) && !isNaN(curPath)) {
        newSubdoc = newSubdoc[curPath];
        curPath = '';
      }
      if (newSubdoc == null) {
        break;
      }
      subdoc = newSubdoc;
    } else {
      curPath += curPath.length ? '.' + parts[i + 1] : parts[i + 1];
    }
  }
 
  return subdoc;
};