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

11.11% Statements 1/9
0% Branches 0/16
0% Functions 0/2
11.11% Lines 1/9

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                        1x                                          
'use strict';
 
/**
 * Set a populated virtual value on a document's `$$populatedVirtuals` value
 *
 * @param {*} populatedVirtuals A document's `$$populatedVirtuals`
 * @param {*} name The virtual name
 * @param {*} v The result of the populate query
 * @param {*} options The populate options. This function handles `justOne` and `count` options.
 * @returns {Array<Document>|Document|Object|Array<Object>} the populated virtual value that was set
 */
 
module.exports = function setPopulatedVirtualValue(populatedVirtuals, name, v, options) {
  if (options.justOne || options.count) {
    populatedVirtuals[name] = Array.isArray(v) ?
      v[0] :
      v;
 
    if (typeof populatedVirtuals[name] !== 'object') {
      populatedVirtuals[name] = options.count ? v : null;
    }
  } else {
    populatedVirtuals[name] = Array.isArray(v) ?
      v :
      v == null ? [] : [v];
 
    populatedVirtuals[name] = populatedVirtuals[name].filter(function(doc) {
      return doc && typeof doc === 'object';
    });
  }
 
  return populatedVirtuals[name];
};