All files / mongoose/lib/types/documentArray/methods index.js

19.56% Statements 27/138
7.2% Branches 8/111
22.72% Functions 5/22
19.85% Lines 27/136

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395    1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x   1x           1x                                 6x                                                                                                                                                                                                                                                                               1x 1x     1x     1x                                                                                                                                                                                                                                                                                                                         2x     2x 2x   2x                     2x       2x     2x       1x                                                    
'use strict';
 
const ArrayMethods = require('../../array/methods');
const Document = require('../../../document');
const castObjectId = require('../../../cast/objectid');
const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
const internalToObjectOptions = require('../../../options').internalToObjectOptions;
const utils = require('../../../utils');
const isBsonType = require('../../../helpers/isBsonType');
 
const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
const arraySchemaSymbol = require('../../../helpers/symbols').arraySchemaSymbol;
const documentArrayParent = require('../../../helpers/symbols').documentArrayParent;
 
const _baseToString = Array.prototype.toString;
 
const methods = {
  /*!
   * ignore
   */
 
  toBSON() {
    return this.toObject(internalToObjectOptions);
  },
 
  toString() {
    return _baseToString.call(this.__array.map(subdoc => {
      if (subdoc != null && subdoc.$__ != null) {
        return subdoc.toString();
      }
      return subdoc;
    }));
  },
 
  /*!
   * ignore
   */
 
  getArrayParent() {
    return this[arrayParentSymbol];
  },
 
  /**
   * Overrides MongooseArray#cast
   *
   * @method _cast
   * @api private
   * @memberOf MongooseDocumentArray
   */
 
  _cast(value, index, options) {
    if (this[arraySchemaSymbol] == null) {
      return value;
    }
    let Constructor = this[arraySchemaSymbol].casterConstructor;
    const isInstance = Constructor.$isMongooseDocumentArray ?
      utils.isMongooseDocumentArray(value) :
      value instanceof Constructor;
    if (isInstance ||
        // Hack re: #5001, see #5005
        (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) {
      if (!(value[documentArrayParent] && value.__parentArray)) {
        // value may have been created using array.create()
        value[documentArrayParent] = this[arrayParentSymbol];
        value.__parentArray = this;
      }
      value.$setIndex(index);
      return value;
    }
 
    if (value === undefined || value === null) {
      return null;
    }
 
    // handle cast('string') or cast(ObjectId) etc.
    // only objects are permitted so we can safely assume that
    // non-objects are to be interpreted as _id
    if (Buffer.isBuffer(value) ||
        isBsonType(value, 'ObjectId') || !utils.isObject(value)) {
      value = { _id: value };
    }
 
    if (value &&
        Constructor.discriminators &&
        Constructor.schema &&
        Constructor.schema.options &&
        Constructor.schema.options.discriminatorKey) {
      if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
          Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
        Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
      } else {
        const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]);
        if (constructorByValue) {
          Constructor = constructorByValue;
        }
      }
    }
 
    if (Constructor.$isMongooseDocumentArray) {
      return Constructor.cast(value, this, undefined, undefined, index);
    }
    const ret = new Constructor(value, this, options, undefined, index);
    ret.isNew = true;
    return ret;
  },
 
  /**
   * Searches array items for the first document with a matching _id.
   *
   * #### Example:
   *
   *     const embeddedDoc = m.array.id(some_id);
   *
   * @return {EmbeddedDocument|null} the subdocument or null if not found.
   * @param {ObjectId|String|Number|Buffer} id
   * @TODO cast to the _id based on schema for proper comparison
   * @method id
   * @api public
   * @memberOf MongooseDocumentArray
   */
 
  id(id) {
    let casted;
    let sid;
    let _id;
 
    try {
      casted = castObjectId(id).toString();
    } catch (e) {
      casted = null;
    }
 
    for (const val of this) {
      if (!val) {
        continue;
      }
 
      _id = val.get('_id');
 
      if (_id === null || typeof _id === 'undefined') {
        continue;
      } else if (_id instanceof Document) {
        sid || (sid = String(id));
        if (sid == _id._id) {
          return val;
        }
      } else if (!isBsonType(id, 'ObjectId') && !isBsonType(_id, 'ObjectId')) {
        if (id == _id || utils.deepEqual(id, _id)) {
          return val;
        }
      } else if (casted == _id) {
        return val;
      }
    }
 
    return null;
  },
 
  /**
   * Returns a native js Array of plain js objects
   *
   * #### Note:
   *
   * _Each sub-document is converted to a plain object by calling its `#toObject` method._
   *
   * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion
   * @return {Array}
   * @method toObject
   * @api public
   * @memberOf MongooseDocumentArray
   */
 
  toObject(options) {
    // `[].concat` coerces the return value into a vanilla JS array, rather
    // than a Mongoose array.
    return [].concat(this.map(function(doc) {
      Iif (doc == null) {
        return null;
      }
      Iif (typeof doc.toObject !== 'function') {
        return doc;
      }
      return doc.toObject(options);
    }));
  },
 
  $toObject() {
    return this.constructor.prototype.toObject.apply(this, arguments);
  },
 
  /**
   * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
   *
   * @param {...Object} [args]
   * @api public
   * @method push
   * @memberOf MongooseDocumentArray
   */
 
  push() {
    const ret = ArrayMethods.push.apply(this, arguments);
 
    _updateParentPopulated(this);
 
    return ret;
  },
 
  /**
   * Pulls items from the array atomically.
   *
   * @param {...Object} [args]
   * @api public
   * @method pull
   * @memberOf MongooseDocumentArray
   */
 
  pull() {
    const ret = ArrayMethods.pull.apply(this, arguments);
 
    _updateParentPopulated(this);
 
    return ret;
  },
 
  /**
   * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
   * @api private
   */
 
  shift() {
    const ret = ArrayMethods.shift.apply(this, arguments);
 
    _updateParentPopulated(this);
 
    return ret;
  },
 
  /**
   * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
   * @api private
   */
 
  splice() {
    const ret = ArrayMethods.splice.apply(this, arguments);
 
    _updateParentPopulated(this);
 
    return ret;
  },
 
  /**
   * Helper for console.log
   *
   * @method inspect
   * @api public
   * @memberOf MongooseDocumentArray
   */
 
  inspect() {
    return this.toObject();
  },
 
  /**
   * Creates a subdocument casted to this schema.
   *
   * This is the same subdocument constructor used for casting.
   *
   * @param {Object} obj the value to cast to this arrays SubDocument schema
   * @method create
   * @api public
   * @memberOf MongooseDocumentArray
   */
 
  create(obj) {
    let Constructor = this[arraySchemaSymbol].casterConstructor;
    if (obj &&
        Constructor.discriminators &&
        Constructor.schema &&
        Constructor.schema.options &&
        Constructor.schema.options.discriminatorKey) {
      if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
          Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
        Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
      } else {
        const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]);
        if (constructorByValue) {
          Constructor = constructorByValue;
        }
      }
    }
 
    return new Constructor(obj, this);
  },
 
  /*!
   * ignore
   */
 
  notify(event) {
    const _this = this;
    return function notify(val, _arr) {
      _arr = _arr || _this;
      let i = _arr.length;
      while (i--) {
        if (_arr[i] == null) {
          continue;
        }
        switch (event) {
          // only swap for save event for now, we may change this to all event types later
          case 'save':
            val = _this[i];
            break;
          default:
            // NO-OP
            break;
        }
 
        if (utils.isMongooseArray(_arr[i])) {
          notify(val, _arr[i]);
        } else if (_arr[i]) {
          _arr[i].emit(event, val);
        }
      }
    };
  },
 
  set(i, val, skipModified) {
    const arr = this.__array;
    if (skipModified) {
      arr[i] = val;
      return this;
    }
    const value = methods._cast.call(this, val, i);
    methods._markModified.call(this, i);
    arr[i] = value;
    return this;
  },
 
  _markModified(elem, embeddedPath) {
    const parent = this[arrayParentSymbol];
    let dirtyPath;
 
    Eif (parent) {
      dirtyPath = this[arrayPathSymbol];
 
      Iif (arguments.length) {
        if (embeddedPath != null) {
          // an embedded doc bubbled up the change
          const index = elem.__index;
          dirtyPath = dirtyPath + '.' + index + '.' + embeddedPath;
        } else {
          // directly set an index
          dirtyPath = dirtyPath + '.' + elem;
        }
      }
 
      Iif (dirtyPath != null && dirtyPath.endsWith('.$')) {
        return this;
      }
 
      parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent);
    }
 
    return this;
  }
};
 
module.exports = methods;
 
/**
 * If this is a document array, each element may contain single
 * populated paths, so we need to modify the top-level document's
 * populated cache. See gh-8247, gh-8265.
 * @param {Array} arr
 * @api private
 */
 
function _updateParentPopulated(arr) {
  const parent = arr[arrayParentSymbol];
  if (!parent || parent.$__.populated == null) return;
 
  const populatedPaths = Object.keys(parent.$__.populated).
    filter(p => p.startsWith(arr[arrayPathSymbol] + '.'));
 
  for (const path of populatedPaths) {
    const remnant = path.slice((arr[arrayPathSymbol] + '.').length);
    if (!Array.isArray(parent.$__.populated[path].value)) {
      continue;
    }
 
    parent.$__.populated[path].value = arr.map(val => val.$populated(remnant));
  }
}