All files / mongoose/lib/helpers/populate markArraySubdocsPopulated.js

8.69% Statements 2/23
0% Branches 0/15
0% Functions 0/1
9.52% Lines 2/21

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 47 48 49 50    1x                               1x                                                              
'use strict';
 
const utils = require('../../utils');
 
/**
 * If populating a path within a document array, make sure each
 * subdoc within the array knows its subpaths are populated.
 *
 * #### Example:
 *
 *     const doc = await Article.findOne().populate('comments.author');
 *     doc.comments[0].populated('author'); // Should be set
 *
 * @param {Document} doc
 * @param {Object} [populated]
 * @api private
 */
 
module.exports = function markArraySubdocsPopulated(doc, populated) {
  if (doc._doc._id == null || populated == null || populated.length === 0) {
    return;
  }
 
  const id = String(doc._doc._id);
  for (const item of populated) {
    if (item.isVirtual) {
      continue;
    }
    const path = item.path;
    const pieces = path.split('.');
    for (let i = 0; i < pieces.length - 1; ++i) {
      const subpath = pieces.slice(0, i + 1).join('.');
      const rest = pieces.slice(i + 1).join('.');
      const val = doc.get(subpath);
      if (val == null) {
        continue;
      }
 
      if (utils.isMongooseDocumentArray(val)) {
        for (let j = 0; j < val.length; ++j) {
          if (val[j]) {
            val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
          }
        }
        break;
      }
    }
  }
};