All files / mongoose/lib/types map.js

57.14% Statements 68/119
48.88% Branches 44/90
47.05% Functions 8/17
56.77% Lines 67/118

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    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x               7x 5x   7x 7x 7x 7x   7x                                                   25x       25x 25x 11x   14x                                                   14x       14x 14x           14x 7x 7x 7x       7x 7x     7x   7x                                               7x 7x     7x                               7x   7x 7x 7x     7x 3x             10x 3x   7x 7x                                                                                                   8x                 8x                                                                                 7x       7x 7x     7x       1x 1x               1x           1x           1x           1x                             1x             1x                             14x 14x     14x     14x     14x         1x  
'use strict';
 
const Mixed = require('../schema/mixed');
const MongooseError = require('../error/mongooseError');
const clone = require('../helpers/clone');
const deepEqual = require('../utils').deepEqual;
const getConstructorName = require('../helpers/getConstructorName');
const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
const util = require('util');
const specialProperties = require('../helpers/specialProperties');
const isBsonType = require('../helpers/isBsonType');
const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths');
 
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
 
/*!
 * ignore
 */
 
class MongooseMap extends Map {
  constructor(v, path, doc, schemaType) {
    if (getConstructorName(v) === 'Object') {
      v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []);
    }
    super(v);
    this.$__parent = doc != null && doc.$__ != null ? doc : null;
    this.$__path = path;
    this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType;
 
    this.$__runDeferred();
  }
 
  $init(key, value) {
    checkValidKey(key);
 
    super.set(key, value);
 
    if (value != null && value.$isSingleNested) {
      value.$basePath = this.$__path + '.' + key;
    }
  }
 
  $__set(key, value) {
    super.set(key, value);
  }
 
  /**
   * Overwrites native Map's `get()` function to support Mongoose getters.
   *
   * @api public
   * @method get
   * @memberOf Map
   */
 
  get(key, options) {
    Iif (isBsonType(key, 'ObjectId')) {
      key = key.toString();
    }
 
    options = options || {};
    if (options.getters === false) {
      return super.get(key);
    }
    return this.$__schemaType.applyGetters(super.get(key), this.$__parent);
  }
 
  /**
   * Overwrites native Map's `set()` function to support setters, `populate()`,
   * and change tracking. Note that Mongoose maps _only_ support strings and
   * ObjectIds as keys.
   *
   * Keys also cannot:
   * - be named after special properties `prototype`, `constructor`, and `__proto__`
   * - start with a dollar sign (`$`)
   * - contain any dots (`.`)
   *
   * #### Example:
   *
   *     doc.myMap.set('test', 42); // works
   *     doc.myMap.set({ obj: 42 }, 42); // Throws "Mongoose maps only support string keys"
   *     doc.myMap.set(10, 42); // Throws "Mongoose maps only support string keys"
   *     doc.myMap.set("$test", 42); // Throws "Mongoose maps do not support keys that start with "$", got "$test""
   *
   * @api public
   * @method set
   * @memberOf Map
   */
 
  set(key, value) {
    Iif (isBsonType(key, 'ObjectId')) {
      key = key.toString();
    }
 
    checkValidKey(key);
    value = handleSpreadDoc(value);
 
    // Weird, but because you can't assign to `this` before calling `super()`
    // you can't get access to `$__schemaType` to cast in the initial call to
    // `set()` from the `super()` constructor.
 
    if (this.$__schemaType == null) {
      this.$__deferred = this.$__deferred || [];
      this.$__deferred.push({ key: key, value: value });
      return;
    }
 
    let _fullPath;
    const parent = this.$__parent;
    const populated = parent != null && parent.$__ && parent.$__.populated ?
      parent.$populated(fullPath.call(this), true) || parent.$populated(this.$__path, true) :
      null;
    const priorVal = this.get(key);
 
    Iif (populated != null) {
      if (this.$__schemaType.$isSingleNested) {
        throw new MongooseError(
          'Cannot manually populate single nested subdoc underneath Map ' +
          `at path "${this.$__path}". Try using an array instead of a Map.`
        );
      }
      if (Array.isArray(value) && this.$__schemaType.$isMongooseArray) {
        value = value.map(v => {
          if (v.$__ == null) {
            v = new populated.options[populateModelSymbol](v);
          }
          // Doesn't support single nested "in-place" populate
          v.$__.wasPopulated = { value: v._doc._id };
          return v;
        });
      } else if (value != null) {
        if (value.$__ == null) {
          value = new populated.options[populateModelSymbol](value);
        }
        // Doesn't support single nested "in-place" populate
        value.$__.wasPopulated = { value: value._doc._id };
      }
    } else {
      try {
        const options = this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested ?
          { path: fullPath.call(this) } :
          null;
        value = this.$__schemaType.applySetters(
          value,
          this.$__parent,
          false,
          this.get(key),
          options
        );
      } catch (error) {
        if (this.$__parent != null && this.$__parent.$__ != null) {
          this.$__parent.invalidate(fullPath.call(this), error);
          return;
        }
        throw error;
      }
    }
 
    super.set(key, value);
 
    Eif (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) {
      const path = fullPath.call(this);
      parent.markModified(path);
      // If overwriting the full document array or subdoc, make sure to clean up any paths that were modified
      // before re: #15108
      if (this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested) {
        cleanModifiedSubpaths(parent, path);
      }
    }
 
    // Delay calculating full path unless absolutely necessary, because string
    // concatenation is a bottleneck re: #13171
    function fullPath() {
      if (_fullPath) {
        return _fullPath;
      }
      _fullPath = this.$__path + '.' + key;
      return _fullPath;
    }
  }
 
  /**
   * Overwrites native Map's `clear()` function to support change tracking.
   *
   * @api public
   * @method clear
   * @memberOf Map
   */
 
  clear() {
    super.clear();
    const parent = this.$__parent;
    if (parent != null) {
      parent.markModified(this.$__path);
    }
  }
 
  /**
   * Overwrites native Map's `delete()` function to support change tracking.
   *
   * @api public
   * @method delete
   * @memberOf Map
   */
 
  delete(key) {
    if (isBsonType(key, 'ObjectId')) {
      key = key.toString();
    }
 
    this.set(key, undefined);
    return super.delete(key);
  }
 
  /**
   * Converts this map to a native JavaScript Map so the MongoDB driver can serialize it.
   *
   * @api public
   * @method toBSON
   * @memberOf Map
   */
 
  toBSON() {
    return new Map(this);
  }
 
  toObject(options) {
    Iif (options && options.flattenMaps) {
      const ret = {};
      const keys = this.keys();
      for (const key of keys) {
        ret[key] = clone(this.get(key), options);
      }
      return ret;
    }
 
    return new Map(this);
  }
 
  $toObject() {
    return this.constructor.prototype.toObject.apply(this, arguments);
  }
 
  /**
   * Converts this map to a native JavaScript Map for `JSON.stringify()`. Set
   * the `flattenMaps` option to convert this map to a POJO instead.
   *
   * #### Example:
   *
   *     doc.myMap.toJSON() instanceof Map; // true
   *     doc.myMap.toJSON({ flattenMaps: true }) instanceof Map; // false
   *
   * @api public
   * @method toJSON
   * @param {Object} [options]
   * @param {Boolean} [options.flattenMaps=false] set to `true` to convert the map to a POJO rather than a native JavaScript map
   * @memberOf Map
   */
 
  toJSON(options) {
    if (typeof (options && options.flattenMaps) === 'boolean' ? options.flattenMaps : true) {
      const ret = {};
      const keys = this.keys();
      for (const key of keys) {
        ret[key] = clone(this.get(key), options);
      }
      return ret;
    }
 
    return new Map(this);
  }
 
  inspect() {
    return new Map(this);
  }
 
  $__runDeferred() {
    Iif (!this.$__deferred) {
      return;
    }
 
    for (const keyValueObject of this.$__deferred) {
      this.set(keyValueObject.key, keyValueObject.value);
    }
 
    this.$__deferred = null;
  }
}
 
Eif (util.inspect.custom) {
  Object.defineProperty(MongooseMap.prototype, util.inspect.custom, {
    enumerable: false,
    writable: false,
    configurable: false,
    value: MongooseMap.prototype.inspect
  });
}
 
Object.defineProperty(MongooseMap.prototype, '$__set', {
  enumerable: false,
  writable: true,
  configurable: false
});
 
Object.defineProperty(MongooseMap.prototype, '$__parent', {
  enumerable: false,
  writable: true,
  configurable: false
});
 
Object.defineProperty(MongooseMap.prototype, '$__path', {
  enumerable: false,
  writable: true,
  configurable: false
});
 
Object.defineProperty(MongooseMap.prototype, '$__schemaType', {
  enumerable: false,
  writable: true,
  configurable: false
});
 
/**
 * Set to `true` for all Mongoose map instances
 *
 * @api public
 * @property $isMongooseMap
 * @memberOf MongooseMap
 * @instance
 */
 
Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', {
  enumerable: false,
  writable: false,
  configurable: false,
  value: true
});
 
Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', {
  enumerable: false,
  writable: false,
  configurable: false,
  value: true
});
 
/**
 * Since maps are stored as objects under the hood, keys must be strings
 * and can't contain any invalid characters
 * @param {String} key
 * @api private
 */
 
function checkValidKey(key) {
  const keyType = typeof key;
  Iif (keyType !== 'string') {
    throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`);
  }
  Iif (key.startsWith('$')) {
    throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`);
  }
  Iif (key.includes('.')) {
    throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`);
  }
  Iif (specialProperties.has(key)) {
    throw new Error(`Mongoose maps do not support reserved key name "${key}"`);
  }
}
 
module.exports = MongooseMap;