cqm-models 3.1.1 → 3.1.2

Sign up to get free protection for your applications and to get access to all the features.
data/dist/index.js CHANGED
@@ -3408,7 +3408,7 @@ function Any(key, options) {
3408
3408
  Any.prototype = Object.create(mongoose.SchemaType.prototype);
3409
3409
 
3410
3410
  function RecursiveCast(any) {
3411
- if (any && any.value && any.unit) {
3411
+ if (any && any.value !== undefined && any.unit) {
3412
3412
  return new cql.Quantity(any.value, any.unit);
3413
3413
  }
3414
3414
 
@@ -7027,8 +7027,8 @@ class Unit {
7027
7027
  * concatenated string. Basically it checks to see if the string
7028
7028
  * needs to be enclosed either in parentheses or square brackets.
7029
7029
  *
7030
- * The string is enclosed if it is not a number, does not start with
7031
- * a parenthesis or square bracket, and includes a period, and asterisk,
7030
+ * The string is enclosed if it is not a number, is not already enclosed in a pair of
7031
+ * parentheses or square brackets, and includes a period, and asterisk,
7032
7032
  * a slash or a blank space.
7033
7033
  *
7034
7034
  * @param str the string
@@ -7044,7 +7044,7 @@ class Unit {
7044
7044
  if (intUtils_.isNumericString(str)) {
7045
7045
  ret = str;
7046
7046
  } else {
7047
- if (str.charAt(0) === '(' || str.charAt(0) === '[') {
7047
+ if (str.charAt(0) === '(' && str.endsWith(')') || str.charAt(0) === '[' && str.endsWith(']')) {
7048
7048
  ret = str;
7049
7049
  } else if (/[./* ]/.test(str)) {
7050
7050
  ret = startChar + str + endChar;
@@ -9926,7 +9926,7 @@ var objectKeys = Object.keys || function (obj) {
9926
9926
  };
9927
9927
 
9928
9928
  }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9929
- },{"object-assign":323,"util/":105}],103:[function(require,module,exports){
9929
+ },{"object-assign":325,"util/":105}],103:[function(require,module,exports){
9930
9930
  if (typeof Object.create === 'function') {
9931
9931
  // implementation from standard node.js 'util' module
9932
9932
  module.exports = function inherits(ctor, superCtor) {
@@ -10548,7 +10548,7 @@ function hasOwnProperty(obj, prop) {
10548
10548
  }
10549
10549
 
10550
10550
  }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10551
- },{"./support/isBuffer":104,"_process":324,"inherits":103}],106:[function(require,module,exports){
10551
+ },{"./support/isBuffer":104,"_process":326,"inherits":103}],106:[function(require,module,exports){
10552
10552
  'use strict'
10553
10553
 
10554
10554
  exports.byteLength = byteLength
@@ -16326,7 +16326,7 @@ module.exports = ret;
16326
16326
  },{"./es5":13}]},{},[4])(4)
16327
16327
  }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
16328
16328
  }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
16329
- },{"_process":324,"timers":328}],108:[function(require,module,exports){
16329
+ },{"_process":326,"timers":330}],108:[function(require,module,exports){
16330
16330
  (function (global){(function (){
16331
16331
  /**
16332
16332
  * Module dependencies.
@@ -18260,6 +18260,11 @@ Long.prototype.toNumber = function() {
18260
18260
  return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();
18261
18261
  };
18262
18262
 
18263
+ /** Converts the Long to a BigInt (arbitrary precision). */
18264
+ Long.prototype.toBigInt = function () {
18265
+ return BigInt(this.toString());
18266
+ }
18267
+
18263
18268
  /**
18264
18269
  * Return the JSON value.
18265
18270
  *
@@ -18894,6 +18899,15 @@ Long.fromNumber = function(value) {
18894
18899
  }
18895
18900
  };
18896
18901
 
18902
+ /**
18903
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
18904
+ * @param {bigint} value - The number in question
18905
+ * @returns {Long} The corresponding Long value
18906
+ */
18907
+ Long.fromBigInt = function(value) {
18908
+ return Long.fromString(value.toString(10), 10);
18909
+ }
18910
+
18897
18911
  /**
18898
18912
  * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
18899
18913
  *
@@ -19593,7 +19607,7 @@ module.exports.ObjectID = ObjectID;
19593
19607
  module.exports.ObjectId = ObjectID;
19594
19608
 
19595
19609
  }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
19596
- },{"./parser/utils":124,"_process":324,"buffer":128,"util":331}],121:[function(require,module,exports){
19610
+ },{"./parser/utils":124,"_process":326,"buffer":128,"util":333}],121:[function(require,module,exports){
19597
19611
  (function (Buffer){(function (){
19598
19612
  'use strict';
19599
19613
 
@@ -21349,6 +21363,8 @@ var serializeInto = function serializeInto(
21349
21363
  index = serializeString(buffer, key, value, index, true);
21350
21364
  } else if (type === 'number') {
21351
21365
  index = serializeNumber(buffer, key, value, index, true);
21366
+ } else if(type === 'bigint') {
21367
+ throw new TypeError('Unsupported type BigInt, please use Decimal128');
21352
21368
  } else if (type === 'boolean') {
21353
21369
  index = serializeBoolean(buffer, key, value, index, true);
21354
21370
  } else if (value instanceof Date || isDate(value)) {
@@ -21460,6 +21476,8 @@ var serializeInto = function serializeInto(
21460
21476
  index = serializeString(buffer, key, value, index);
21461
21477
  } else if (type === 'number') {
21462
21478
  index = serializeNumber(buffer, key, value, index);
21479
+ } else if(type === 'bigint') {
21480
+ throw new TypeError('Unsupported type BigInt, please use Decimal128');
21463
21481
  } else if (type === 'boolean') {
21464
21482
  index = serializeBoolean(buffer, key, value, index);
21465
21483
  } else if (value instanceof Date || isDate(value)) {
@@ -21563,6 +21581,8 @@ var serializeInto = function serializeInto(
21563
21581
  index = serializeString(buffer, key, value, index);
21564
21582
  } else if (type === 'number') {
21565
21583
  index = serializeNumber(buffer, key, value, index);
21584
+ } else if(type === 'bigint') {
21585
+ throw new TypeError('Unsupported type BigInt, please use Decimal128');
21566
21586
  } else if (type === 'boolean') {
21567
21587
  index = serializeBoolean(buffer, key, value, index);
21568
21588
  } else if (value instanceof Date || isDate(value)) {
@@ -21949,7 +21969,7 @@ module.exports = Symbol;
21949
21969
  module.exports.Symbol = Symbol;
21950
21970
 
21951
21971
  }).call(this)}).call(this,require("buffer").Buffer)
21952
- },{"buffer":128,"util":331}],127:[function(require,module,exports){
21972
+ },{"buffer":128,"util":333}],127:[function(require,module,exports){
21953
21973
  // Licensed under the Apache License, Version 2.0 (the "License");
21954
21974
  // you may not use this file except in compliance with the License.
21955
21975
  // You may obtain a copy of the License at
@@ -40713,7 +40733,7 @@ function decorateNextFn(fn) {
40713
40733
  module.exports = Kareem;
40714
40734
 
40715
40735
  }).call(this)}).call(this,require('_process'))
40716
- },{"_process":324}],182:[function(require,module,exports){
40736
+ },{"_process":326}],182:[function(require,module,exports){
40717
40737
  'use strict';
40718
40738
 
40719
40739
  Object.defineProperty(exports, '__esModule', { value: true });
@@ -41430,13 +41450,13 @@ var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
41430
41450
  function months(length) {
41431
41451
  switch (length) {
41432
41452
  case "narrow":
41433
- return monthsNarrow;
41453
+ return [].concat(monthsNarrow);
41434
41454
 
41435
41455
  case "short":
41436
- return monthsShort;
41456
+ return [].concat(monthsShort);
41437
41457
 
41438
41458
  case "long":
41439
- return monthsLong;
41459
+ return [].concat(monthsLong);
41440
41460
 
41441
41461
  case "numeric":
41442
41462
  return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
@@ -41454,13 +41474,13 @@ var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
41454
41474
  function weekdays(length) {
41455
41475
  switch (length) {
41456
41476
  case "narrow":
41457
- return weekdaysNarrow;
41477
+ return [].concat(weekdaysNarrow);
41458
41478
 
41459
41479
  case "short":
41460
- return weekdaysShort;
41480
+ return [].concat(weekdaysShort);
41461
41481
 
41462
41482
  case "long":
41463
- return weekdaysLong;
41483
+ return [].concat(weekdaysLong);
41464
41484
 
41465
41485
  case "numeric":
41466
41486
  return ["1", "2", "3", "4", "5", "6", "7"];
@@ -41476,13 +41496,13 @@ var erasNarrow = ["B", "A"];
41476
41496
  function eras(length) {
41477
41497
  switch (length) {
41478
41498
  case "narrow":
41479
- return erasNarrow;
41499
+ return [].concat(erasNarrow);
41480
41500
 
41481
41501
  case "short":
41482
- return erasShort;
41502
+ return [].concat(erasShort);
41483
41503
 
41484
41504
  case "long":
41485
- return erasLong;
41505
+ return [].concat(erasLong);
41486
41506
 
41487
41507
  default:
41488
41508
  return null;
@@ -42497,7 +42517,7 @@ var IANAZone = /*#__PURE__*/function (_Zone) {
42497
42517
 
42498
42518
  IANAZone.parseGMTOffset = function parseGMTOffset(specifier) {
42499
42519
  if (specifier) {
42500
- var match = specifier.match(/^Etc\/GMT([+-]\d{1,2})$/i);
42520
+ var match = specifier.match(/^Etc\/GMT(0|[+-]\d{1,2})$/i);
42501
42521
 
42502
42522
  if (match) {
42503
42523
  return -60 * parseInt(match[1]);
@@ -42540,8 +42560,10 @@ var IANAZone = /*#__PURE__*/function (_Zone) {
42540
42560
  ;
42541
42561
 
42542
42562
  _proto.offset = function offset(ts) {
42543
- var date = new Date(ts),
42544
- dtf = makeDTF(this.name),
42563
+ var date = new Date(ts);
42564
+ if (isNaN(date)) return NaN;
42565
+
42566
+ var dtf = makeDTF(this.name),
42545
42567
  _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date),
42546
42568
  year = _ref2[0],
42547
42569
  month = _ref2[1],
@@ -43200,12 +43222,16 @@ var PolyDateFormatter = /*#__PURE__*/function () {
43200
43222
  if (dt.zone.universal && this.hasIntl) {
43201
43223
  // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.
43202
43224
  // That is why fixed-offset TZ is set to that unless it is:
43203
- // 1. Outside of the supported range Etc/GMT-14 to Etc/GMT+12.
43204
- // 2. Not a whole hour, e.g. UTC+4:30.
43225
+ // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.
43226
+ // 2. Unsupported by the browser:
43227
+ // - some do not support Etc/
43228
+ // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata
43205
43229
  var gmtOffset = -1 * (dt.offset / 60);
43230
+ var offsetZ = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset;
43231
+ var isOffsetZoneSupported = IANAZone.isValidZone(offsetZ);
43206
43232
 
43207
- if (gmtOffset >= -14 && gmtOffset <= 12 && gmtOffset % 1 === 0) {
43208
- z = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset;
43233
+ if (dt.offset !== 0 && isOffsetZoneSupported) {
43234
+ z = offsetZ;
43209
43235
  this.dt = dt;
43210
43236
  } else {
43211
43237
  // Not all fixed-offset zones like Etc/+4:30 are present in tzdata.
@@ -43742,9 +43768,14 @@ function extractISODuration(match) {
43742
43768
  secondStr = match[7],
43743
43769
  millisecondsStr = match[8];
43744
43770
  var hasNegativePrefix = s[0] === "-";
43771
+ var negativeSeconds = secondStr && secondStr[0] === "-";
43772
+
43773
+ var maybeNegate = function maybeNegate(num, force) {
43774
+ if (force === void 0) {
43775
+ force = false;
43776
+ }
43745
43777
 
43746
- var maybeNegate = function maybeNegate(num) {
43747
- return num && hasNegativePrefix ? -num : num;
43778
+ return num !== undefined && (force || num && hasNegativePrefix) ? -num : num;
43748
43779
  };
43749
43780
 
43750
43781
  return [{
@@ -43754,8 +43785,8 @@ function extractISODuration(match) {
43754
43785
  days: maybeNegate(parseInteger(dayStr)),
43755
43786
  hours: maybeNegate(parseInteger(hourStr)),
43756
43787
  minutes: maybeNegate(parseInteger(minuteStr)),
43757
- seconds: maybeNegate(parseInteger(secondStr)),
43758
- milliseconds: maybeNegate(parseMillis(millisecondsStr))
43788
+ seconds: maybeNegate(parseInteger(secondStr), secondStr === "-0"),
43789
+ milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
43759
43790
  }];
43760
43791
  } // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York
43761
43792
  // and not just that we're in -240 *right now*. But since I don't think these are used that often
@@ -43860,14 +43891,14 @@ var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeEx
43860
43891
  var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
43861
43892
  var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset);
43862
43893
  var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset);
43863
- var extractISOOrdinalDataAndTime = combineExtractors(extractISOOrdinalData, extractISOTime);
43894
+ var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset);
43864
43895
  var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset);
43865
43896
  /**
43866
43897
  * @private
43867
43898
  */
43868
43899
 
43869
43900
  function parseISODate(s) {
43870
- return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDataAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
43901
+ return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
43871
43902
  }
43872
43903
  function parseRFC2822Date(s) {
43873
43904
  return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);
@@ -44095,7 +44126,7 @@ var Duration = /*#__PURE__*/function () {
44095
44126
  }, opts));
44096
44127
  }
44097
44128
  /**
44098
- * Create a Duration from a JavaScript object with keys like 'years' and 'hours.
44129
+ * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
44099
44130
  * If this object is empty then a zero milliseconds duration is returned.
44100
44131
  * @param {Object} obj - the object to create the DateTime from
44101
44132
  * @param {number} obj.years
@@ -44487,9 +44518,9 @@ var Duration = /*#__PURE__*/function () {
44487
44518
  /**
44488
44519
  * Get the value of unit.
44489
44520
  * @param {string} unit - a unit such as 'minute' or 'day'
44490
- * @example Duration.fromObject({years: 2, days: 3}).years //=> 2
44491
- * @example Duration.fromObject({years: 2, days: 3}).months //=> 0
44492
- * @example Duration.fromObject({years: 2, days: 3}).days //=> 3
44521
+ * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
44522
+ * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
44523
+ * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
44493
44524
  * @return {number}
44494
44525
  */
44495
44526
  ;
@@ -45195,15 +45226,18 @@ var Interval = /*#__PURE__*/function () {
45195
45226
  }
45196
45227
 
45197
45228
  var s = this.s,
45198
- added,
45229
+ idx = 1,
45199
45230
  next;
45200
45231
  var results = [];
45201
45232
 
45202
45233
  while (s < this.e) {
45203
- added = s.plus(dur);
45234
+ var added = this.start.plus(dur.mapUnits(function (x) {
45235
+ return x * idx;
45236
+ }));
45204
45237
  next = +added > +this.e ? this.e : added;
45205
45238
  results.push(Interval.fromDateTimes(s, next));
45206
45239
  s = next;
45240
+ idx += 1;
45207
45241
  }
45208
45242
 
45209
45243
  return results;
@@ -45290,7 +45324,7 @@ var Interval = /*#__PURE__*/function () {
45290
45324
  var s = this.s > other.s ? this.s : other.s,
45291
45325
  e = this.e < other.e ? this.e : other.e;
45292
45326
 
45293
- if (s > e) {
45327
+ if (s >= e) {
45294
45328
  return null;
45295
45329
  } else {
45296
45330
  return Interval.fromDateTimes(s, e);
@@ -45615,6 +45649,7 @@ var Info = /*#__PURE__*/function () {
45615
45649
  * @param {Object} opts - options
45616
45650
  * @param {string} [opts.locale] - the locale code
45617
45651
  * @param {string} [opts.numberingSystem=null] - the numbering system
45652
+ * @param {string} [opts.locObj=null] - an existing locale object to use
45618
45653
  * @param {string} [opts.outputCalendar='gregory'] - the calendar
45619
45654
  * @example Info.months()[0] //=> 'January'
45620
45655
  * @example Info.months('short')[0] //=> 'Jan'
@@ -45636,10 +45671,12 @@ var Info = /*#__PURE__*/function () {
45636
45671
  locale = _ref$locale === void 0 ? null : _ref$locale,
45637
45672
  _ref$numberingSystem = _ref.numberingSystem,
45638
45673
  numberingSystem = _ref$numberingSystem === void 0 ? null : _ref$numberingSystem,
45674
+ _ref$locObj = _ref.locObj,
45675
+ locObj = _ref$locObj === void 0 ? null : _ref$locObj,
45639
45676
  _ref$outputCalendar = _ref.outputCalendar,
45640
45677
  outputCalendar = _ref$outputCalendar === void 0 ? "gregory" : _ref$outputCalendar;
45641
45678
 
45642
- return Locale.create(locale, numberingSystem, outputCalendar).months(length);
45679
+ return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
45643
45680
  }
45644
45681
  /**
45645
45682
  * Return an array of format month names.
@@ -45650,6 +45687,7 @@ var Info = /*#__PURE__*/function () {
45650
45687
  * @param {Object} opts - options
45651
45688
  * @param {string} [opts.locale] - the locale code
45652
45689
  * @param {string} [opts.numberingSystem=null] - the numbering system
45690
+ * @param {string} [opts.locObj=null] - an existing locale object to use
45653
45691
  * @param {string} [opts.outputCalendar='gregory'] - the calendar
45654
45692
  * @return {[string]}
45655
45693
  */
@@ -45665,10 +45703,12 @@ var Info = /*#__PURE__*/function () {
45665
45703
  locale = _ref2$locale === void 0 ? null : _ref2$locale,
45666
45704
  _ref2$numberingSystem = _ref2.numberingSystem,
45667
45705
  numberingSystem = _ref2$numberingSystem === void 0 ? null : _ref2$numberingSystem,
45706
+ _ref2$locObj = _ref2.locObj,
45707
+ locObj = _ref2$locObj === void 0 ? null : _ref2$locObj,
45668
45708
  _ref2$outputCalendar = _ref2.outputCalendar,
45669
45709
  outputCalendar = _ref2$outputCalendar === void 0 ? "gregory" : _ref2$outputCalendar;
45670
45710
 
45671
- return Locale.create(locale, numberingSystem, outputCalendar).months(length, true);
45711
+ return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
45672
45712
  }
45673
45713
  /**
45674
45714
  * Return an array of standalone week names.
@@ -45677,6 +45717,7 @@ var Info = /*#__PURE__*/function () {
45677
45717
  * @param {Object} opts - options
45678
45718
  * @param {string} [opts.locale] - the locale code
45679
45719
  * @param {string} [opts.numberingSystem=null] - the numbering system
45720
+ * @param {string} [opts.locObj=null] - an existing locale object to use
45680
45721
  * @example Info.weekdays()[0] //=> 'Monday'
45681
45722
  * @example Info.weekdays('short')[0] //=> 'Mon'
45682
45723
  * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
@@ -45694,9 +45735,11 @@ var Info = /*#__PURE__*/function () {
45694
45735
  _ref3$locale = _ref3.locale,
45695
45736
  locale = _ref3$locale === void 0 ? null : _ref3$locale,
45696
45737
  _ref3$numberingSystem = _ref3.numberingSystem,
45697
- numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem;
45738
+ numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem,
45739
+ _ref3$locObj = _ref3.locObj,
45740
+ locObj = _ref3$locObj === void 0 ? null : _ref3$locObj;
45698
45741
 
45699
- return Locale.create(locale, numberingSystem, null).weekdays(length);
45742
+ return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
45700
45743
  }
45701
45744
  /**
45702
45745
  * Return an array of format week names.
@@ -45707,6 +45750,7 @@ var Info = /*#__PURE__*/function () {
45707
45750
  * @param {Object} opts - options
45708
45751
  * @param {string} [opts.locale=null] - the locale code
45709
45752
  * @param {string} [opts.numberingSystem=null] - the numbering system
45753
+ * @param {string} [opts.locObj=null] - an existing locale object to use
45710
45754
  * @return {[string]}
45711
45755
  */
45712
45756
  ;
@@ -45720,9 +45764,11 @@ var Info = /*#__PURE__*/function () {
45720
45764
  _ref4$locale = _ref4.locale,
45721
45765
  locale = _ref4$locale === void 0 ? null : _ref4$locale,
45722
45766
  _ref4$numberingSystem = _ref4.numberingSystem,
45723
- numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem;
45767
+ numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem,
45768
+ _ref4$locObj = _ref4.locObj,
45769
+ locObj = _ref4$locObj === void 0 ? null : _ref4$locObj;
45724
45770
 
45725
- return Locale.create(locale, numberingSystem, null).weekdays(length, true);
45771
+ return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
45726
45772
  }
45727
45773
  /**
45728
45774
  * Return an array of meridiems.
@@ -47013,7 +47059,7 @@ function diffRelative(start, end, opts) {
47013
47059
  }
47014
47060
  }
47015
47061
 
47016
- return format(0, opts.units[opts.units.length - 1]);
47062
+ return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
47017
47063
  }
47018
47064
  /**
47019
47065
  * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
@@ -47140,7 +47186,7 @@ var DateTime = /*#__PURE__*/function () {
47140
47186
 
47141
47187
  DateTime.local = function local(year, month, day, hour, minute, second, millisecond) {
47142
47188
  if (isUndefined(year)) {
47143
- return new DateTime({});
47189
+ return DateTime.now();
47144
47190
  } else {
47145
47191
  return quickDT({
47146
47192
  year: year,
@@ -47408,8 +47454,8 @@ var DateTime = /*#__PURE__*/function () {
47408
47454
  * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
47409
47455
  * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
47410
47456
  * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
47411
- * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
47412
- * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
47457
+ * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
47458
+ * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
47413
47459
  * @example DateTime.fromISO('2016-05-25T09:08:34.123')
47414
47460
  * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
47415
47461
  * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
@@ -47784,7 +47830,21 @@ var DateTime = /*#__PURE__*/function () {
47784
47830
  _proto.set = function set(values) {
47785
47831
  if (!this.isValid) return this;
47786
47832
  var normalized = normalizeObject(values, normalizeUnit, []),
47787
- settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday);
47833
+ settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday),
47834
+ containsOrdinal = !isUndefined(normalized.ordinal),
47835
+ containsGregorYear = !isUndefined(normalized.year),
47836
+ containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
47837
+ containsGregor = containsGregorYear || containsGregorMD,
47838
+ definiteWeekDef = normalized.weekYear || normalized.weekNumber;
47839
+
47840
+ if ((containsGregor || containsOrdinal) && definiteWeekDef) {
47841
+ throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
47842
+ }
47843
+
47844
+ if (containsGregorMD && containsOrdinal) {
47845
+ throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
47846
+ }
47847
+
47788
47848
  var mixed;
47789
47849
 
47790
47850
  if (settingWeekStuff) {
@@ -48368,7 +48428,7 @@ var DateTime = /*#__PURE__*/function () {
48368
48428
  * @param {Object} options - options that affect the output
48369
48429
  * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
48370
48430
  * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
48371
- * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
48431
+ * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
48372
48432
  * @param {boolean} [options.round=true] - whether to round the numbers in the output.
48373
48433
  * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
48374
48434
  * @param {string} options.locale - override the locale of this DateTime
@@ -48392,9 +48452,18 @@ var DateTime = /*#__PURE__*/function () {
48392
48452
  zone: this.zone
48393
48453
  }),
48394
48454
  padding = options.padding ? this < base ? -options.padding : options.padding : 0;
48455
+ var units = ["years", "months", "days", "hours", "minutes", "seconds"];
48456
+ var unit = options.unit;
48457
+
48458
+ if (Array.isArray(options.unit)) {
48459
+ units = options.unit;
48460
+ unit = undefined;
48461
+ }
48462
+
48395
48463
  return diffRelative(base, this.plus(padding), Object.assign(options, {
48396
48464
  numeric: "always",
48397
- units: ["years", "months", "days", "hours", "minutes", "seconds"]
48465
+ units: units,
48466
+ unit: unit
48398
48467
  }));
48399
48468
  }
48400
48469
  /**
@@ -48681,7 +48750,7 @@ var DateTime = /*#__PURE__*/function () {
48681
48750
  /**
48682
48751
  * Get the week year
48683
48752
  * @see https://en.wikipedia.org/wiki/ISO_week_date
48684
- * @example DateTime.local(2014, 11, 31).weekYear //=> 2015
48753
+ * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
48685
48754
  * @type {number}
48686
48755
  */
48687
48756
 
@@ -48737,7 +48806,7 @@ var DateTime = /*#__PURE__*/function () {
48737
48806
  key: "monthShort",
48738
48807
  get: function get() {
48739
48808
  return this.isValid ? Info.months("short", {
48740
- locale: this.locale
48809
+ locObj: this.loc
48741
48810
  })[this.month - 1] : null;
48742
48811
  }
48743
48812
  /**
@@ -48751,7 +48820,7 @@ var DateTime = /*#__PURE__*/function () {
48751
48820
  key: "monthLong",
48752
48821
  get: function get() {
48753
48822
  return this.isValid ? Info.months("long", {
48754
- locale: this.locale
48823
+ locObj: this.loc
48755
48824
  })[this.month - 1] : null;
48756
48825
  }
48757
48826
  /**
@@ -48765,7 +48834,7 @@ var DateTime = /*#__PURE__*/function () {
48765
48834
  key: "weekdayShort",
48766
48835
  get: function get() {
48767
48836
  return this.isValid ? Info.weekdays("short", {
48768
- locale: this.locale
48837
+ locObj: this.loc
48769
48838
  })[this.weekday - 1] : null;
48770
48839
  }
48771
48840
  /**
@@ -48779,7 +48848,7 @@ var DateTime = /*#__PURE__*/function () {
48779
48848
  key: "weekdayLong",
48780
48849
  get: function get() {
48781
48850
  return this.isValid ? Info.weekdays("long", {
48782
- locale: this.locale
48851
+ locObj: this.loc
48783
48852
  })[this.weekday - 1] : null;
48784
48853
  }
48785
48854
  /**
@@ -49138,7 +49207,7 @@ function friendlyDateTime(dateTimeish) {
49138
49207
  }
49139
49208
  }
49140
49209
 
49141
- var VERSION = "1.26.0";
49210
+ var VERSION = "1.28.0";
49142
49211
 
49143
49212
  exports.DateTime = DateTime;
49144
49213
  exports.Duration = Duration;
@@ -49235,11 +49304,14 @@ exports.Schema = require('./schema');
49235
49304
  *
49236
49305
  * ####Types:
49237
49306
  *
49238
- * - [ObjectId](#types-objectid-js)
49239
- * - [Buffer](#types-buffer-js)
49240
- * - [SubDocument](#types-embedded-js)
49241
- * - [Array](#types-array-js)
49242
- * - [DocumentArray](#types-documentarray-js)
49307
+ * - [Array](/docs/schematypes.html#arrays)
49308
+ * - [Buffer](/docs/schematypes.html#buffers)
49309
+ * - [Embedded](/docs/schematypes.html#schemas)
49310
+ * - [DocumentArray](/docs/api/documentarraypath.html)
49311
+ * - [Decimal128](/docs/api.html#mongoose_Mongoose-Decimal128)
49312
+ * - [ObjectId](/docs/schematypes.html#objectids)
49313
+ * - [Map](/docs/schematypes.html#maps)
49314
+ * - [Subdocument](/docs/schematypes.html#schemas)
49243
49315
  *
49244
49316
  * Using this exposed access to the `ObjectId` type, we can construct ids on demand.
49245
49317
  *
@@ -49322,7 +49394,7 @@ if (typeof window !== 'undefined') {
49322
49394
  }
49323
49395
 
49324
49396
  }).call(this)}).call(this,require("buffer").Buffer)
49325
- },{"./document_provider.js":194,"./driver":195,"./drivers/browser":199,"./error/index":203,"./promise_provider":271,"./schema":273,"./schematype.js":294,"./types":302,"./utils.js":306,"./virtualtype":307,"buffer":128}],185:[function(require,module,exports){
49397
+ },{"./document_provider.js":194,"./driver":195,"./drivers/browser":199,"./error/index":203,"./promise_provider":273,"./schema":275,"./schematype.js":296,"./types":304,"./utils.js":308,"./virtualtype":309,"buffer":128}],185:[function(require,module,exports){
49326
49398
  /*!
49327
49399
  * Module dependencies.
49328
49400
  */
@@ -49424,7 +49496,7 @@ Document.$emitter = new EventEmitter();
49424
49496
  Document.ValidationError = ValidationError;
49425
49497
  module.exports = exports = Document;
49426
49498
 
49427
- },{"./document":193,"./error/index":203,"./helpers/isObject":233,"./helpers/model/applyHooks":235,"./schema":273,"./types/objectid":304,"events":176}],186:[function(require,module,exports){
49499
+ },{"./document":193,"./error/index":203,"./helpers/isObject":235,"./helpers/model/applyHooks":237,"./schema":275,"./types/objectid":306,"events":176}],186:[function(require,module,exports){
49428
49500
  'use strict';
49429
49501
 
49430
49502
  /*!
@@ -49436,6 +49508,7 @@ const StrictModeError = require('./error/strict');
49436
49508
  const Types = require('./schema/index');
49437
49509
  const castTextSearch = require('./schema/operators/text');
49438
49510
  const get = require('./helpers/get');
49511
+ const getConstructorName = require('./helpers/getConstructorName');
49439
49512
  const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue');
49440
49513
  const isOperator = require('./helpers/query/isOperator');
49441
49514
  const util = require('util');
@@ -49694,7 +49767,7 @@ module.exports = function cast(schema, obj, options, context) {
49694
49767
  }
49695
49768
  } else if (val == null) {
49696
49769
  continue;
49697
- } else if (val.constructor.name === 'Object') {
49770
+ } else if (getConstructorName(val) === 'Object') {
49698
49771
  any$conditionals = Object.keys(val).some(isOperator);
49699
49772
 
49700
49773
  if (!any$conditionals) {
@@ -49789,7 +49862,7 @@ function _cast(val, numbertype, context) {
49789
49862
  }
49790
49863
  }
49791
49864
  }
49792
- },{"./error/cast":201,"./error/strict":213,"./helpers/discriminator/getSchemaDiscriminatorByValue":223,"./helpers/get":228,"./helpers/isMongooseObject":232,"./helpers/isObject":233,"./helpers/query/isOperator":242,"./schema/index":281,"./schema/operators/text":290,"util":331}],187:[function(require,module,exports){
49865
+ },{"./error/cast":201,"./error/strict":213,"./helpers/discriminator/getSchemaDiscriminatorByValue":224,"./helpers/get":229,"./helpers/getConstructorName":230,"./helpers/isMongooseObject":234,"./helpers/isObject":235,"./helpers/query/isOperator":244,"./schema/index":283,"./schema/operators/text":292,"util":333}],187:[function(require,module,exports){
49793
49866
  'use strict';
49794
49867
 
49795
49868
  const CastError = require('../error/cast');
@@ -49904,7 +49977,7 @@ module.exports = function castDecimal128(value) {
49904
49977
  assert.ok(false);
49905
49978
  };
49906
49979
  }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
49907
- },{"../../../is-buffer/index.js":178,"../types/decimal128":299,"assert":102}],190:[function(require,module,exports){
49980
+ },{"../../../is-buffer/index.js":178,"../types/decimal128":301,"assert":102}],190:[function(require,module,exports){
49908
49981
  'use strict';
49909
49982
 
49910
49983
  const assert = require('assert');
@@ -50019,7 +50092,7 @@ module.exports = function castString(value, path) {
50019
50092
  };
50020
50093
 
50021
50094
  },{"../error/cast":201}],193:[function(require,module,exports){
50022
- (function (Buffer,process){(function (){
50095
+ (function (Buffer){(function (){
50023
50096
  'use strict';
50024
50097
 
50025
50098
  /*!
@@ -50047,6 +50120,7 @@ const get = require('./helpers/get');
50047
50120
  const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
50048
50121
  const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');
50049
50122
  const idGetter = require('./plugins/idGetter');
50123
+ const immediate = require('./helpers/immediate');
50050
50124
  const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
50051
50125
  const isExclusive = require('./helpers/projection/isExclusive');
50052
50126
  const inspect = require('util').inspect;
@@ -50069,6 +50143,7 @@ const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
50069
50143
  const getSymbol = require('./helpers/symbols').getSymbol;
50070
50144
  const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
50071
50145
  const scopeSymbol = require('./helpers/symbols').scopeSymbol;
50146
+ const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
50072
50147
 
50073
50148
  let DocumentArray;
50074
50149
  let MongooseArray;
@@ -50098,9 +50173,8 @@ function Document(obj, fields, skipId, options) {
50098
50173
  options = Object.assign({}, options);
50099
50174
  const defaults = get(options, 'defaults', true);
50100
50175
  options.defaults = defaults;
50101
-
50102
50176
  // Support `browserDocument.js` syntax
50103
- if (this.schema == null) {
50177
+ if (this.$__schema == null) {
50104
50178
  const _schema = utils.isObject(fields) && !fields.instanceOfSchema ?
50105
50179
  new Schema(fields) :
50106
50180
  fields;
@@ -50117,12 +50191,11 @@ function Document(obj, fields, skipId, options) {
50117
50191
  this.$__.$options = options || {};
50118
50192
  this.$locals = {};
50119
50193
  this.$op = null;
50120
-
50121
50194
  if (obj != null && typeof obj !== 'object') {
50122
50195
  throw new ObjectParameterError(obj, 'obj', 'Document');
50123
50196
  }
50124
50197
 
50125
- const schema = this.schema;
50198
+ const schema = this.$__schema;
50126
50199
 
50127
50200
  if (typeof fields === 'boolean' || fields === 'throw') {
50128
50201
  this.$__.strictMode = fields;
@@ -50225,6 +50298,17 @@ for (const i in EventEmitter.prototype) {
50225
50298
  Document[i] = EventEmitter.prototype[i];
50226
50299
  }
50227
50300
 
50301
+ /**
50302
+ * The document's internal schema.
50303
+ *
50304
+ * @api private
50305
+ * @property schema
50306
+ * @memberOf Document
50307
+ * @instance
50308
+ */
50309
+
50310
+ Document.prototype.$__schema;
50311
+
50228
50312
  /**
50229
50313
  * The document's schema.
50230
50314
  *
@@ -50276,6 +50360,28 @@ Object.defineProperty(Document.prototype, '$locals', {
50276
50360
 
50277
50361
  Document.prototype.isNew;
50278
50362
 
50363
+ /**
50364
+ * Set this property to add additional query filters when Mongoose saves this document and `isNew` is false.
50365
+ *
50366
+ * ####Example:
50367
+ *
50368
+ * // Make sure `save()` never updates a soft deleted document.
50369
+ * schema.pre('save', function() {
50370
+ * this.$where = { isDeleted: false };
50371
+ * });
50372
+ *
50373
+ * @api public
50374
+ * @property $where
50375
+ * @memberOf Document
50376
+ * @instance
50377
+ */
50378
+
50379
+ Object.defineProperty(Document.prototype, '$where', {
50380
+ configurable: false,
50381
+ enumerable: false,
50382
+ writable: true
50383
+ });
50384
+
50279
50385
  /**
50280
50386
  * The string version of this documents _id.
50281
50387
  *
@@ -50354,7 +50460,7 @@ function $__hasIncludedChildren(fields) {
50354
50460
  */
50355
50461
 
50356
50462
  function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) {
50357
- const paths = Object.keys(doc.schema.paths);
50463
+ const paths = Object.keys(doc.$__schema.paths);
50358
50464
  const plen = paths.length;
50359
50465
 
50360
50466
  for (let i = 0; i < plen; ++i) {
@@ -50366,12 +50472,11 @@ function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isB
50366
50472
  continue;
50367
50473
  }
50368
50474
 
50369
- const type = doc.schema.paths[p];
50370
- const path = p.indexOf('.') === -1 ? [p] : p.split('.');
50475
+ const type = doc.$__schema.paths[p];
50476
+ const path = type.splitPath();
50371
50477
  const len = path.length;
50372
50478
  let included = false;
50373
50479
  let doc_ = doc._doc;
50374
-
50375
50480
  for (let j = 0; j < len; ++j) {
50376
50481
  if (doc_ == null) {
50377
50482
  break;
@@ -50480,7 +50585,7 @@ function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isB
50480
50585
  Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) {
50481
50586
  const doc = {};
50482
50587
 
50483
- const paths = Object.keys(this.schema.paths).
50588
+ const paths = Object.keys(this.$__schema.paths).
50484
50589
  // Don't build up any paths that are underneath a map, we don't know
50485
50590
  // what the keys will be
50486
50591
  filter(p => !p.includes('$*'));
@@ -50499,7 +50604,7 @@ Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasInclu
50499
50604
  }
50500
50605
  }
50501
50606
 
50502
- const path = p.split('.');
50607
+ const path = this.$__schema.paths[p].splitPath();
50503
50608
  const len = path.length;
50504
50609
  const last = len - 1;
50505
50610
  let curPath = '';
@@ -50600,6 +50705,7 @@ Document.prototype.$__init = function(doc, opts) {
50600
50705
  }
50601
50706
  child.$__.parent = this;
50602
50707
  }
50708
+ item._childDocs = [];
50603
50709
  }
50604
50710
  }
50605
50711
 
@@ -50611,7 +50717,6 @@ Document.prototype.$__init = function(doc, opts) {
50611
50717
  this.constructor.emit('init', this);
50612
50718
 
50613
50719
  this.$__._id = this._id;
50614
-
50615
50720
  return this;
50616
50721
  };
50617
50722
 
@@ -50680,12 +50785,12 @@ function init(self, obj, doc, opts, prefix) {
50680
50785
  function _init(index) {
50681
50786
  i = keys[index];
50682
50787
  path = prefix + i;
50683
- schema = self.schema.path(path);
50788
+ schema = self.$__schema.path(path);
50684
50789
 
50685
50790
  // Should still work if not a model-level discriminator, but should not be
50686
50791
  // necessary. This is *only* to catch the case where we queried using the
50687
50792
  // base model and the discriminated model has a projection
50688
- if (self.schema.$isRootDiscriminator && !self.$__isSelected(path)) {
50793
+ if (self.$__schema.$isRootDiscriminator && !self.$__isSelected(path)) {
50689
50794
  return;
50690
50795
  }
50691
50796
 
@@ -50790,10 +50895,10 @@ Document.prototype.update = function update() {
50790
50895
 
50791
50896
  Document.prototype.updateOne = function updateOne(doc, options, callback) {
50792
50897
  const query = this.constructor.updateOne({ _id: this._id }, doc, options);
50793
- query._pre(cb => {
50898
+ query.pre(cb => {
50794
50899
  this.constructor._middleware.execPre('updateOne', this, [this], cb);
50795
50900
  });
50796
- query._post(cb => {
50901
+ query.post(cb => {
50797
50902
  this.constructor._middleware.execPost('updateOne', this, [this], {}, cb);
50798
50903
  });
50799
50904
 
@@ -50815,7 +50920,7 @@ Document.prototype.updateOne = function updateOne(doc, options, callback) {
50815
50920
  *
50816
50921
  * ####Valid options:
50817
50922
  *
50818
- * - same as in [Model.replaceOne](#model_Model.replaceOne)
50923
+ * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne)
50819
50924
  *
50820
50925
  * @see Model.replaceOne #model_Model.replaceOne
50821
50926
  * @param {Object} doc
@@ -50858,12 +50963,22 @@ Document.prototype.replaceOne = function replaceOne() {
50858
50963
 
50859
50964
  Document.prototype.$session = function $session(session) {
50860
50965
  if (arguments.length === 0) {
50966
+ if (this.$__.session != null && this.$__.session.hasEnded) {
50967
+ this.$__.session = null;
50968
+ return null;
50969
+ }
50861
50970
  return this.$__.session;
50862
50971
  }
50972
+
50973
+ if (session != null && session.hasEnded) {
50974
+ throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' +
50975
+ 'called `endSession()` on the session you are passing to `$session()`.');
50976
+ }
50977
+
50863
50978
  this.$__.session = session;
50864
50979
 
50865
50980
  if (!this.ownerDocument) {
50866
- const subdocs = this.$__getAllSubdocs();
50981
+ const subdocs = this.$getAllSubdocs();
50867
50982
  for (const child of subdocs) {
50868
50983
  child.$session(session);
50869
50984
  }
@@ -50893,10 +51008,10 @@ Document.prototype.overwrite = function overwrite(obj) {
50893
51008
  continue;
50894
51009
  }
50895
51010
  // Explicitly skip version key
50896
- if (this.schema.options.versionKey && key === this.schema.options.versionKey) {
51011
+ if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) {
50897
51012
  continue;
50898
51013
  }
50899
- if (this.schema.options.discriminatorKey && key === this.schema.options.discriminatorKey) {
51014
+ if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) {
50900
51015
  continue;
50901
51016
  }
50902
51017
  this.$set(key, obj[key]);
@@ -50920,7 +51035,6 @@ Document.prototype.overwrite = function overwrite(obj) {
50920
51035
  */
50921
51036
 
50922
51037
  Document.prototype.$set = function $set(path, val, type, options) {
50923
-
50924
51038
  if (utils.isPOJO(type)) {
50925
51039
  options = type;
50926
51040
  type = undefined;
@@ -50930,6 +51044,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
50930
51044
  const merge = options.merge;
50931
51045
  const adhoc = type && type !== true;
50932
51046
  const constructing = type === true;
51047
+ const typeKey = this.$__schema.options.typeKey;
50933
51048
  let adhocs;
50934
51049
  let keys;
50935
51050
  let i = 0;
@@ -50943,7 +51058,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
50943
51058
 
50944
51059
  if (adhoc) {
50945
51060
  adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
50946
- adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options);
51061
+ adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options);
50947
51062
  }
50948
51063
 
50949
51064
  if (path == null) {
@@ -50983,7 +51098,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
50983
51098
  for (let i = 0; i < len; ++i) {
50984
51099
  key = keys[i];
50985
51100
  const pathName = prefix + key;
50986
- pathtype = this.schema.pathType(pathName);
51101
+ pathtype = this.$__schema.pathType(pathName);
50987
51102
 
50988
51103
  // On initial set, delete any nested keys if we're going to overwrite
50989
51104
  // them to ensure we keep the user's key order.
@@ -50996,6 +51111,9 @@ Document.prototype.$set = function $set(path, val, type, options) {
50996
51111
  delete this._doc[key];
50997
51112
  // Make sure we set `{}` back even if we minimize re: gh-8565
50998
51113
  options = Object.assign({}, options, { _skipMinimizeTopLevel: true });
51114
+ } else {
51115
+ // Make sure we set `{_skipMinimizeTopLevel: false}` if don't have overwrite: gh-10441
51116
+ options = Object.assign({}, options, { _skipMinimizeTopLevel: false });
50999
51117
  }
51000
51118
 
51001
51119
  const someCondition = typeof path[key] === 'object' &&
@@ -51006,9 +51124,9 @@ Document.prototype.$set = function $set(path, val, type, options) {
51006
51124
  pathtype !== 'real' &&
51007
51125
  pathtype !== 'adhocOrUndefined' &&
51008
51126
  !(this.$__path(pathName) instanceof MixedSchema) &&
51009
- !(this.schema.paths[pathName] &&
51010
- this.schema.paths[pathName].options &&
51011
- this.schema.paths[pathName].options.ref);
51127
+ !(this.$__schema.paths[pathName] &&
51128
+ this.$__schema.paths[pathName].options &&
51129
+ this.$__schema.paths[pathName].options.ref);
51012
51130
 
51013
51131
  if (someCondition) {
51014
51132
  this.$__.$setCalled.add(prefix + key);
@@ -51027,8 +51145,8 @@ Document.prototype.$set = function $set(path, val, type, options) {
51027
51145
  if (pathtype === 'real' || pathtype === 'virtual') {
51028
51146
  // Check for setting single embedded schema to document (gh-3535)
51029
51147
  let p = path[key];
51030
- if (this.schema.paths[pathName] &&
51031
- this.schema.paths[pathName].$isSingleNested &&
51148
+ if (this.$__schema.paths[pathName] &&
51149
+ this.$__schema.paths[pathName].$isSingleNested &&
51032
51150
  path[key] instanceof Document) {
51033
51151
  p = p.toObject({ virtuals: false, transform: false });
51034
51152
  }
@@ -51053,7 +51171,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
51053
51171
  this.$__.$setCalled.add(path);
51054
51172
  }
51055
51173
 
51056
- let pathType = this.schema.pathType(path);
51174
+ let pathType = this.$__schema.pathType(path);
51057
51175
  if (pathType === 'adhocOrUndefined') {
51058
51176
  pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true });
51059
51177
  }
@@ -51104,8 +51222,8 @@ Document.prototype.$set = function $set(path, val, type, options) {
51104
51222
  const parts = path.indexOf('.') === -1 ? [path] : path.split('.');
51105
51223
 
51106
51224
  // Might need to change path for top-level alias
51107
- if (typeof this.schema.aliases[parts[0]] == 'string') {
51108
- parts[0] = this.schema.aliases[parts[0]];
51225
+ if (typeof this.$__schema.aliases[parts[0]] == 'string') {
51226
+ parts[0] = this.$__schema.aliases[parts[0]];
51109
51227
  }
51110
51228
 
51111
51229
  if (pathType === 'adhocOrUndefined' && strict) {
@@ -51116,12 +51234,12 @@ Document.prototype.$set = function $set(path, val, type, options) {
51116
51234
  const subpath = parts.slice(0, i + 1).join('.');
51117
51235
 
51118
51236
  // If path is underneath a virtual, bypass everything and just set it.
51119
- if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') {
51237
+ if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') {
51120
51238
  mpath.set(path, val, this);
51121
51239
  return this;
51122
51240
  }
51123
51241
 
51124
- schema = this.schema.path(subpath);
51242
+ schema = this.$__schema.path(subpath);
51125
51243
  if (schema == null) {
51126
51244
  continue;
51127
51245
  }
@@ -51145,7 +51263,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
51145
51263
  return this;
51146
51264
  }
51147
51265
  } else if (pathType === 'virtual') {
51148
- schema = this.schema.virtualpath(path);
51266
+ schema = this.$__schema.virtualpath(path);
51149
51267
  schema.applySetters(val, this);
51150
51268
  return this;
51151
51269
  } else {
@@ -51265,25 +51383,20 @@ Document.prototype.$set = function $set(path, val, type, options) {
51265
51383
 
51266
51384
  let popOpts;
51267
51385
  if (schema.options &&
51268
- Array.isArray(schema.options[this.schema.options.typeKey]) &&
51269
- schema.options[this.schema.options.typeKey].length &&
51270
- schema.options[this.schema.options.typeKey][0].ref &&
51271
- _isManuallyPopulatedArray(val, schema.options[this.schema.options.typeKey][0].ref)) {
51272
- if (this.ownerDocument) {
51273
- popOpts = { [populateModelSymbol]: val[0].constructor };
51274
- this.ownerDocument().populated(this.$__fullPath(path),
51275
- val.map(function(v) { return v._id; }), popOpts);
51276
- } else {
51277
- popOpts = { [populateModelSymbol]: val[0].constructor };
51278
- this.populated(path, val.map(function(v) { return v._id; }), popOpts);
51279
- }
51386
+ Array.isArray(schema.options[typeKey]) &&
51387
+ schema.options[typeKey].length &&
51388
+ schema.options[typeKey][0].ref &&
51389
+ _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) {
51390
+ popOpts = { [populateModelSymbol]: val[0].constructor };
51391
+ this.populated(path, val.map(function(v) { return v._id; }), popOpts);
51392
+
51280
51393
  for (const doc of val) {
51281
51394
  doc.$__.wasPopulated = true;
51282
51395
  }
51283
51396
  didPopulate = true;
51284
51397
  }
51285
51398
 
51286
- if (this.schema.singleNestedPaths[path] == null) {
51399
+ if (this.$__schema.singleNestedPaths[path] == null) {
51287
51400
  // If this path is underneath a single nested schema, we'll call the setter
51288
51401
  // later in `$__set()` because we don't take `_doc` when we iterate through
51289
51402
  // a single nested doc. That's to make sure we get the correct context.
@@ -51442,7 +51555,7 @@ Document.prototype.$__shouldModify = function(pathToMark, path, constructing, pa
51442
51555
  // Re: the note about gh-7196, `val` is the raw value without casting or
51443
51556
  // setters if the full path is under a single nested subdoc because we don't
51444
51557
  // want to double run setters. So don't set it as modified. See gh-7264.
51445
- if (this.schema.singleNestedPaths[path] != null) {
51558
+ if (this.$__schema.singleNestedPaths[path] != null) {
51446
51559
  return false;
51447
51560
  }
51448
51561
 
@@ -51605,20 +51718,20 @@ Document.prototype.get = function(path, type, options) {
51605
51718
  let adhoc;
51606
51719
  options = options || {};
51607
51720
  if (type) {
51608
- adhoc = this.schema.interpretAsType(path, type, this.schema.options);
51721
+ adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options);
51609
51722
  }
51610
51723
 
51611
51724
  let schema = this.$__path(path);
51612
51725
  if (schema == null) {
51613
- schema = this.schema.virtualpath(path);
51726
+ schema = this.$__schema.virtualpath(path);
51614
51727
  }
51615
51728
  if (schema instanceof MixedSchema) {
51616
- const virtual = this.schema.virtualpath(path);
51729
+ const virtual = this.$__schema.virtualpath(path);
51617
51730
  if (virtual != null) {
51618
51731
  schema = virtual;
51619
51732
  }
51620
51733
  }
51621
- const pieces = path.split('.');
51734
+ const pieces = path.indexOf('.') === -1 ? [path] : path.split('.');
51622
51735
  let obj = this._doc;
51623
51736
 
51624
51737
  if (schema instanceof VirtualType) {
@@ -51626,8 +51739,8 @@ Document.prototype.get = function(path, type, options) {
51626
51739
  }
51627
51740
 
51628
51741
  // Might need to change path for top-level alias
51629
- if (typeof this.schema.aliases[pieces[0]] == 'string') {
51630
- pieces[0] = this.schema.aliases[pieces[0]];
51742
+ if (typeof this.$__schema.aliases[pieces[0]] == 'string') {
51743
+ pieces[0] = this.$__schema.aliases[pieces[0]];
51631
51744
  }
51632
51745
 
51633
51746
  for (let i = 0, l = pieces.length; i < l; i++) {
@@ -51652,7 +51765,7 @@ Document.prototype.get = function(path, type, options) {
51652
51765
 
51653
51766
  if (schema != null && options.getters !== false) {
51654
51767
  obj = schema.applyGetters(obj, this);
51655
- } else if (this.schema.nested[path] && options.virtuals) {
51768
+ } else if (this.$__schema.nested[path] && options.virtuals) {
51656
51769
  // Might need to apply virtuals if this is a nested path
51657
51770
  return applyVirtuals(this, utils.clone(obj) || {}, { path: path });
51658
51771
  }
@@ -51683,7 +51796,7 @@ Document.prototype.$__path = function(path) {
51683
51796
  if (adhocType) {
51684
51797
  return adhocType;
51685
51798
  }
51686
- return this.schema.path(path);
51799
+ return this.$__schema.path(path);
51687
51800
  };
51688
51801
 
51689
51802
  /**
@@ -52218,6 +52331,7 @@ Document.prototype.isDirectSelected = function isDirectSelected(path) {
52218
52331
  * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.
52219
52332
  * @param {Object} [options] internal options
52220
52333
  * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths.
52334
+ * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.
52221
52335
  * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred
52222
52336
  * @return {Promise} Promise
52223
52337
  * @api public
@@ -52238,7 +52352,17 @@ Document.prototype.validate = function(pathsToValidate, options, callback) {
52238
52352
  this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack });
52239
52353
  }
52240
52354
 
52241
- if (typeof pathsToValidate === 'function') {
52355
+ if (arguments.length === 1) {
52356
+ if (typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) {
52357
+ options = arguments[0];
52358
+ callback = null;
52359
+ pathsToValidate = null;
52360
+ } else if (typeof arguments[0] === 'function') {
52361
+ callback = arguments[0];
52362
+ options = null;
52363
+ pathsToValidate = null;
52364
+ }
52365
+ } else if (typeof pathsToValidate === 'function') {
52242
52366
  callback = pathsToValidate;
52243
52367
  options = null;
52244
52368
  pathsToValidate = null;
@@ -52247,6 +52371,10 @@ Document.prototype.validate = function(pathsToValidate, options, callback) {
52247
52371
  options = pathsToValidate;
52248
52372
  pathsToValidate = null;
52249
52373
  }
52374
+ if (options && typeof options.pathsToSkip === 'string') {
52375
+ const isOnePathOnly = options.pathsToSkip.indexOf(' ') === -1;
52376
+ options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(' ');
52377
+ }
52250
52378
 
52251
52379
  return promiseOrCallback(callback, cb => {
52252
52380
  if (parallelValidate != null) {
@@ -52266,7 +52394,7 @@ Document.prototype.validate = function(pathsToValidate, options, callback) {
52266
52394
 
52267
52395
  function _evaluateRequiredFunctions(doc) {
52268
52396
  Object.keys(doc.$__.activePaths.states.require).forEach(path => {
52269
- const p = doc.schema.path(path);
52397
+ const p = doc.$__schema.path(path);
52270
52398
 
52271
52399
  if (p != null && typeof p.originalRequiredValue === 'function') {
52272
52400
  doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc);
@@ -52299,7 +52427,7 @@ function _getPathsToValidate(doc) {
52299
52427
  Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths);
52300
52428
  function addToPaths(p) { paths.add(p); }
52301
52429
 
52302
- const subdocs = doc.$__getAllSubdocs();
52430
+ const subdocs = doc.$getAllSubdocs();
52303
52431
  const modifiedPaths = doc.modifiedPaths();
52304
52432
  for (const subdoc of subdocs) {
52305
52433
  if (subdoc.$basePath) {
@@ -52326,7 +52454,7 @@ function _getPathsToValidate(doc) {
52326
52454
  // gh-661: if a whole array is modified, make sure to run validation on all
52327
52455
  // the children as well
52328
52456
  for (const path of paths) {
52329
- const _pathType = doc.schema.path(path);
52457
+ const _pathType = doc.$__schema.path(path);
52330
52458
  if (!_pathType ||
52331
52459
  !_pathType.$isMongooseArray ||
52332
52460
  // To avoid potential performance issues, skip doc arrays whose children
@@ -52355,12 +52483,12 @@ function _getPathsToValidate(doc) {
52355
52483
 
52356
52484
  const flattenOptions = { skipArrays: true };
52357
52485
  for (const pathToCheck of paths) {
52358
- if (doc.schema.nested[pathToCheck]) {
52486
+ if (doc.$__schema.nested[pathToCheck]) {
52359
52487
  let _v = doc.$__getValue(pathToCheck);
52360
52488
  if (isMongooseObject(_v)) {
52361
52489
  _v = _v.toObject({ transform: false });
52362
52490
  }
52363
- const flat = flatten(_v, pathToCheck, flattenOptions, doc.schema);
52491
+ const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema);
52364
52492
  Object.keys(flat).forEach(addToPaths);
52365
52493
  }
52366
52494
  }
@@ -52369,11 +52497,11 @@ function _getPathsToValidate(doc) {
52369
52497
  // Single nested paths (paths embedded under single nested subdocs) will
52370
52498
  // be validated on their own when we call `validate()` on the subdoc itself.
52371
52499
  // Re: gh-8468
52372
- if (doc.schema.singleNestedPaths.hasOwnProperty(path)) {
52500
+ if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) {
52373
52501
  paths.delete(path);
52374
52502
  continue;
52375
52503
  }
52376
- const _pathType = doc.schema.path(path);
52504
+ const _pathType = doc.$__schema.path(path);
52377
52505
  if (!_pathType || !_pathType.$isSchemaMap) {
52378
52506
  continue;
52379
52507
  }
@@ -52409,11 +52537,13 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
52409
52537
  (typeof options === 'object') &&
52410
52538
  ('validateModifiedOnly' in options);
52411
52539
 
52540
+ const pathsToSkip = get(options, 'pathsToSkip', null);
52541
+
52412
52542
  let shouldValidateModifiedOnly;
52413
52543
  if (hasValidateModifiedOnlyOption) {
52414
52544
  shouldValidateModifiedOnly = !!options.validateModifiedOnly;
52415
52545
  } else {
52416
- shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly;
52546
+ shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly;
52417
52547
  }
52418
52548
 
52419
52549
  const _this = this;
@@ -52458,14 +52588,19 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
52458
52588
  pathDetails[0].filter((path) => this.isModified(path)) :
52459
52589
  pathDetails[0];
52460
52590
  const skipSchemaValidators = pathDetails[1];
52591
+ if (typeof pathsToValidate === 'string') {
52592
+ pathsToValidate = pathsToValidate.split(' ');
52593
+ }
52461
52594
  if (Array.isArray(pathsToValidate)) {
52462
52595
  paths = _handlePathsToValidate(paths, pathsToValidate);
52596
+ } else if (pathsToSkip) {
52597
+ paths = _handlePathsToSkip(paths, pathsToSkip);
52463
52598
  }
52464
52599
  if (paths.length === 0) {
52465
- return process.nextTick(function() {
52600
+ return immediate(function() {
52466
52601
  const error = _complete();
52467
52602
  if (error) {
52468
- return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
52603
+ return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
52469
52604
  callback(error);
52470
52605
  });
52471
52606
  }
@@ -52476,17 +52611,11 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
52476
52611
  const validated = {};
52477
52612
  let total = 0;
52478
52613
 
52479
- const complete = function() {
52480
- const error = _complete();
52481
- if (error) {
52482
- return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
52483
- callback(error);
52484
- });
52485
- }
52486
- callback(null, _this);
52487
- };
52614
+ for (const path of paths) {
52615
+ validatePath(path);
52616
+ }
52488
52617
 
52489
- const validatePath = function(path) {
52618
+ function validatePath(path) {
52490
52619
  if (path == null || validated[path]) {
52491
52620
  return;
52492
52621
  }
@@ -52494,8 +52623,8 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
52494
52623
  validated[path] = true;
52495
52624
  total++;
52496
52625
 
52497
- process.nextTick(function() {
52498
- const schemaType = _this.schema.path(path);
52626
+ immediate(function() {
52627
+ const schemaType = _this.$__schema.path(path);
52499
52628
 
52500
52629
  if (!schemaType) {
52501
52630
  return --total || complete();
@@ -52507,6 +52636,11 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
52507
52636
  return;
52508
52637
  }
52509
52638
 
52639
+ // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141)
52640
+ if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) {
52641
+ return --total || complete();
52642
+ }
52643
+
52510
52644
  let val = _this.$__getValue(path);
52511
52645
 
52512
52646
  // If you `populate()` and get back a null value, required validators
@@ -52537,12 +52671,18 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
52537
52671
  --total || complete();
52538
52672
  }, scope, doValidateOptions);
52539
52673
  });
52540
- };
52674
+ }
52541
52675
 
52542
- const numPaths = paths.length;
52543
- for (let i = 0; i < numPaths; ++i) {
52544
- validatePath(paths[i]);
52676
+ function complete() {
52677
+ const error = _complete();
52678
+ if (error) {
52679
+ return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
52680
+ callback(error);
52681
+ });
52682
+ }
52683
+ callback(null, _this);
52545
52684
  }
52685
+
52546
52686
  };
52547
52687
 
52548
52688
  /*!
@@ -52578,6 +52718,15 @@ function _handlePathsToValidate(paths, pathsToValidate) {
52578
52718
  return ret;
52579
52719
  }
52580
52720
 
52721
+ /*!
52722
+ * ignore
52723
+ */
52724
+ function _handlePathsToSkip(paths, pathsToSkip) {
52725
+ pathsToSkip = new Set(pathsToSkip);
52726
+ paths = paths.filter(p => !pathsToSkip.has(p));
52727
+ return paths;
52728
+ }
52729
+
52581
52730
  /**
52582
52731
  * Executes registered validation rules (skipping asynchronous validators) for this document.
52583
52732
  *
@@ -52597,6 +52746,7 @@ function _handlePathsToValidate(paths, pathsToValidate) {
52597
52746
  * @param {Array|string} pathsToValidate only validate the given paths
52598
52747
  * @param {Object} [options] options for validation
52599
52748
  * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
52749
+ * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.
52600
52750
  * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error.
52601
52751
  * @api public
52602
52752
  */
@@ -52604,6 +52754,11 @@ function _handlePathsToValidate(paths, pathsToValidate) {
52604
52754
  Document.prototype.validateSync = function(pathsToValidate, options) {
52605
52755
  const _this = this;
52606
52756
 
52757
+ if (arguments.length === 1 && typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) {
52758
+ options = arguments[0];
52759
+ pathsToValidate = null;
52760
+ }
52761
+
52607
52762
  const hasValidateModifiedOnlyOption = options &&
52608
52763
  (typeof options === 'object') &&
52609
52764
  ('validateModifiedOnly' in options);
@@ -52612,11 +52767,16 @@ Document.prototype.validateSync = function(pathsToValidate, options) {
52612
52767
  if (hasValidateModifiedOnlyOption) {
52613
52768
  shouldValidateModifiedOnly = !!options.validateModifiedOnly;
52614
52769
  } else {
52615
- shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly;
52770
+ shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly;
52616
52771
  }
52617
52772
 
52773
+ let pathsToSkip = options && options.pathsToSkip;
52774
+
52618
52775
  if (typeof pathsToValidate === 'string') {
52619
- pathsToValidate = pathsToValidate.split(' ');
52776
+ const isOnePathOnly = pathsToValidate.indexOf(' ') === -1;
52777
+ pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(' ');
52778
+ } else if (typeof pathsToSkip === 'string' && pathsToSkip.indexOf(' ') !== -1) {
52779
+ pathsToSkip = pathsToSkip.split(' ');
52620
52780
  }
52621
52781
 
52622
52782
  // only validate required fields when necessary
@@ -52628,6 +52788,8 @@ Document.prototype.validateSync = function(pathsToValidate, options) {
52628
52788
 
52629
52789
  if (Array.isArray(pathsToValidate)) {
52630
52790
  paths = _handlePathsToValidate(paths, pathsToValidate);
52791
+ } else if (Array.isArray(pathsToSkip)) {
52792
+ paths = _handlePathsToSkip(paths, pathsToSkip);
52631
52793
  }
52632
52794
  const validating = {};
52633
52795
 
@@ -52638,7 +52800,7 @@ Document.prototype.validateSync = function(pathsToValidate, options) {
52638
52800
 
52639
52801
  validating[path] = true;
52640
52802
 
52641
- const p = _this.schema.path(path);
52803
+ const p = _this.$__schema.path(path);
52642
52804
  if (!p) {
52643
52805
  return;
52644
52806
  }
@@ -52911,7 +53073,13 @@ Document.prototype.$__reset = function reset() {
52911
53073
  }).
52912
53074
  forEach(function(doc) {
52913
53075
  doc.$__reset();
52914
- _this.$__.activePaths.init(doc.$basePath);
53076
+ if (doc.$__parent === _this) {
53077
+ _this.$__.activePaths.init(doc.$basePath);
53078
+ } else if (doc.$__parent != null && doc.$__parent.ownerDocument) {
53079
+ // If map path underneath subdocument, may end up with a case where
53080
+ // map path is modified but parent still needs to be reset. See gh-10295
53081
+ doc.$__parent.$__reset();
53082
+ }
52915
53083
  });
52916
53084
 
52917
53085
  // clear atomics
@@ -52938,7 +53106,7 @@ Document.prototype.$__reset = function reset() {
52938
53106
  this.$__.validationError = undefined;
52939
53107
  this.errors = undefined;
52940
53108
  _this = this;
52941
- this.schema.requiredPaths().forEach(function(path) {
53109
+ this.$__schema.requiredPaths().forEach(function(path) {
52942
53110
  _this.$__.activePaths.require(path);
52943
53111
  });
52944
53112
 
@@ -52968,7 +53136,7 @@ Document.prototype.$__undoReset = function $__undoReset() {
52968
53136
  }
52969
53137
  }
52970
53138
 
52971
- for (const subdoc of this.$__getAllSubdocs()) {
53139
+ for (const subdoc of this.$getAllSubdocs()) {
52972
53140
  subdoc.$__undoReset();
52973
53141
  }
52974
53142
  };
@@ -52992,7 +53160,6 @@ Document.prototype.$__dirty = function() {
52992
53160
  schema: _this.$__path(path)
52993
53161
  };
52994
53162
  });
52995
-
52996
53163
  // gh-2558: if we had to set a default and the value is not undefined,
52997
53164
  // we have to save as well
52998
53165
  all = all.concat(this.$__.activePaths.map('default', function(path) {
@@ -53036,7 +53203,6 @@ Document.prototype.$__dirty = function() {
53036
53203
  top.value[arrayAtomicsSymbol].$set = top.value;
53037
53204
  }
53038
53205
  });
53039
-
53040
53206
  top = lastPath = null;
53041
53207
  return minimal;
53042
53208
  };
@@ -53059,8 +53225,10 @@ Document.prototype.$__setSchema = function(schema) {
53059
53225
  for (const key of Object.keys(schema.virtuals)) {
53060
53226
  schema.virtuals[key]._applyDefaultGetters();
53061
53227
  }
53062
-
53063
- this.schema = schema;
53228
+ if (schema.path('schema') == null) {
53229
+ this.schema = schema;
53230
+ }
53231
+ this.$__schema = schema;
53064
53232
  this[documentSchemaSymbol] = schema;
53065
53233
  };
53066
53234
 
@@ -53096,21 +53264,25 @@ Document.prototype.$__getArrayPathsToValidate = function() {
53096
53264
  /**
53097
53265
  * Get all subdocs (by bfs)
53098
53266
  *
53099
- * @api private
53100
- * @method $__getAllSubdocs
53267
+ * @api public
53268
+ * @method $getAllSubdocs
53101
53269
  * @memberOf Document
53102
53270
  * @instance
53103
53271
  */
53104
53272
 
53105
- Document.prototype.$__getAllSubdocs = function() {
53273
+ Document.prototype.$getAllSubdocs = function $getAllSubdocs() {
53106
53274
  DocumentArray || (DocumentArray = require('./types/documentarray'));
53107
53275
  Embedded = Embedded || require('./types/embedded');
53108
53276
 
53109
53277
  function docReducer(doc, seed, path) {
53110
53278
  let val = doc;
53279
+ let isNested = false;
53111
53280
  if (path) {
53112
53281
  if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) {
53113
53282
  val = doc._doc[path];
53283
+ } else if (doc instanceof Document && doc[documentSchemaSymbol].nested[path]) {
53284
+ val = doc._doc[path];
53285
+ isNested = true;
53114
53286
  } else {
53115
53287
  val = doc[path];
53116
53288
  }
@@ -53138,18 +53310,18 @@ Document.prototype.$__getAllSubdocs = function() {
53138
53310
  seed.push(doc);
53139
53311
  }
53140
53312
  });
53141
- } else if (val instanceof Document && val.$__isNested) {
53142
- seed = Object.keys(val).reduce(function(seed, path) {
53143
- return docReducer(val, seed, path);
53144
- }, seed);
53313
+ } else if (isNested && val != null) {
53314
+ for (const path of Object.keys(val)) {
53315
+ docReducer(val, seed, path);
53316
+ }
53145
53317
  }
53146
53318
  return seed;
53147
53319
  }
53148
53320
 
53149
- const _this = this;
53150
- const subDocs = Object.keys(this._doc).reduce(function(seed, path) {
53151
- return docReducer(_this, seed, path);
53152
- }, []);
53321
+ const subDocs = [];
53322
+ for (const path of Object.keys(this._doc)) {
53323
+ docReducer(this, subDocs, path);
53324
+ }
53153
53325
 
53154
53326
  return subDocs;
53155
53327
  };
@@ -53159,7 +53331,7 @@ Document.prototype.$__getAllSubdocs = function() {
53159
53331
  */
53160
53332
 
53161
53333
  function applyQueue(doc) {
53162
- const q = doc.schema && doc.schema.callQueue;
53334
+ const q = doc.$__schema && doc.$__schema.callQueue;
53163
53335
  if (!q.length) {
53164
53336
  return;
53165
53337
  }
@@ -53201,7 +53373,7 @@ Document.prototype.$toObject = function(options, json) {
53201
53373
 
53202
53374
  const path = json ? 'toJSON' : 'toObject';
53203
53375
  const baseOptions = get(this, 'constructor.base.options.' + path, {});
53204
- const schemaOptions = get(this, 'schema.options', {});
53376
+ const schemaOptions = get(this, '$__schema.options', {});
53205
53377
  // merge base default options with Schema's set default options if available.
53206
53378
  // `clone` is necessary here because `utils.options` directly modifies the second input.
53207
53379
  defaultOptions = utils.options(defaultOptions, clone(baseOptions));
@@ -53211,10 +53383,6 @@ Document.prototype.$toObject = function(options, json) {
53211
53383
  options = utils.isPOJO(options) ? clone(options) : {};
53212
53384
  options._calledWithOptions = options._calledWithOptions || clone(options);
53213
53385
 
53214
- if (!('flattenMaps' in options)) {
53215
- options.flattenMaps = defaultOptions.flattenMaps;
53216
- }
53217
-
53218
53386
  let _minimize;
53219
53387
  if (options._calledWithOptions.minimize != null) {
53220
53388
  _minimize = options.minimize;
@@ -53224,6 +53392,15 @@ Document.prototype.$toObject = function(options, json) {
53224
53392
  _minimize = schemaOptions.minimize;
53225
53393
  }
53226
53394
 
53395
+ let flattenMaps;
53396
+ if (options._calledWithOptions.flattenMaps != null) {
53397
+ flattenMaps = options.flattenMaps;
53398
+ } else if (defaultOptions.flattenMaps != null) {
53399
+ flattenMaps = defaultOptions.flattenMaps;
53400
+ } else {
53401
+ flattenMaps = schemaOptions.flattenMaps;
53402
+ }
53403
+
53227
53404
  // The original options that will be passed to `clone()`. Important because
53228
53405
  // `clone()` will recursively call `$toObject()` on embedded docs, so we
53229
53406
  // need the original options the user passed in, plus `_isNested` and
@@ -53231,7 +53408,8 @@ Document.prototype.$toObject = function(options, json) {
53231
53408
  const cloneOptions = Object.assign(utils.clone(options), {
53232
53409
  _isNested: true,
53233
53410
  json: json,
53234
- minimize: _minimize
53411
+ minimize: _minimize,
53412
+ flattenMaps: flattenMaps
53235
53413
  });
53236
53414
 
53237
53415
  if (utils.hasUserDefinedProperty(options, 'getters')) {
@@ -53280,8 +53458,8 @@ Document.prototype.$toObject = function(options, json) {
53280
53458
  applyVirtuals(this, ret, gettersOptions, options);
53281
53459
  }
53282
53460
 
53283
- if (options.versionKey === false && this.schema.options.versionKey) {
53284
- delete ret[this.schema.options.versionKey];
53461
+ if (options.versionKey === false && this.$__schema.options.versionKey) {
53462
+ delete ret[this.$__schema.options.versionKey];
53285
53463
  }
53286
53464
 
53287
53465
  let transform = options.transform;
@@ -53511,7 +53689,7 @@ function minimize(obj) {
53511
53689
  */
53512
53690
 
53513
53691
  function applyVirtuals(self, json, options, toObjectOptions) {
53514
- const schema = self.schema;
53692
+ const schema = self.$__schema;
53515
53693
  const paths = Object.keys(schema.virtuals);
53516
53694
  let i = paths.length;
53517
53695
  const numPaths = i;
@@ -53521,6 +53699,19 @@ function applyVirtuals(self, json, options, toObjectOptions) {
53521
53699
  let v;
53522
53700
  const aliases = get(toObjectOptions, 'aliases', true);
53523
53701
 
53702
+ let virtualsToApply = null;
53703
+ if (Array.isArray(options.virtuals)) {
53704
+ virtualsToApply = new Set(options.virtuals);
53705
+ }
53706
+ else if (options.virtuals && options.virtuals.pathsToSkip) {
53707
+ virtualsToApply = new Set(paths);
53708
+ for (let i = 0; i < options.virtuals.pathsToSkip.length; i++) {
53709
+ if (virtualsToApply.has(options.virtuals.pathsToSkip[i])) {
53710
+ virtualsToApply.delete(options.virtuals.pathsToSkip[i]);
53711
+ }
53712
+ }
53713
+ }
53714
+
53524
53715
  if (!cur) {
53525
53716
  return json;
53526
53717
  }
@@ -53529,6 +53720,10 @@ function applyVirtuals(self, json, options, toObjectOptions) {
53529
53720
  for (i = 0; i < numPaths; ++i) {
53530
53721
  path = paths[i];
53531
53722
 
53723
+ if (virtualsToApply != null && !virtualsToApply.has(path)) {
53724
+ continue;
53725
+ }
53726
+
53532
53727
  // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })`
53533
53728
  if (!aliases && schema.aliases.hasOwnProperty(path)) {
53534
53729
  continue;
@@ -53561,6 +53756,7 @@ function applyVirtuals(self, json, options, toObjectOptions) {
53561
53756
  return json;
53562
53757
  }
53563
53758
 
53759
+
53564
53760
  /*!
53565
53761
  * Applies virtuals properties to `json`.
53566
53762
  *
@@ -53570,7 +53766,7 @@ function applyVirtuals(self, json, options, toObjectOptions) {
53570
53766
  */
53571
53767
 
53572
53768
  function applyGetters(self, json, options) {
53573
- const schema = self.schema;
53769
+ const schema = self.$__schema;
53574
53770
  const paths = Object.keys(schema.paths);
53575
53771
  let i = paths.length;
53576
53772
  let path;
@@ -53625,7 +53821,7 @@ function applyGetters(self, json, options) {
53625
53821
  */
53626
53822
 
53627
53823
  function applySchemaTypeTransforms(self, json) {
53628
- const schema = self.schema;
53824
+ const schema = self.$__schema;
53629
53825
  const paths = Object.keys(schema.paths || {});
53630
53826
  const cur = self._doc;
53631
53827
 
@@ -53668,7 +53864,7 @@ function throwErrorIfPromise(path, transformedValue) {
53668
53864
  */
53669
53865
 
53670
53866
  function omitDeselectedFields(self, json) {
53671
- const schema = self.schema;
53867
+ const schema = self.$__schema;
53672
53868
  const paths = Object.keys(schema.paths || {});
53673
53869
  const cur = self._doc;
53674
53870
 
@@ -53923,6 +54119,34 @@ Document.prototype.populate = function populate() {
53923
54119
  return this;
53924
54120
  };
53925
54121
 
54122
+ /**
54123
+ * Gets all populated documents associated with this document.
54124
+ *
54125
+ * @api public
54126
+ * @return {Array<Document>} array of populated documents. Empty array if there are no populated documents associated with this document.
54127
+ * @memberOf Document
54128
+ * @instance
54129
+ */
54130
+ Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() {
54131
+ let keys = [];
54132
+ if (this.$__.populated != null) {
54133
+ keys = keys.concat(Object.keys(this.$__.populated));
54134
+ }
54135
+ if (this.$$populatedVirtuals != null) {
54136
+ keys = keys.concat(Object.keys(this.$$populatedVirtuals));
54137
+ }
54138
+ let result = [];
54139
+ for (const key of keys) {
54140
+ const value = this.get(key);
54141
+ if (Array.isArray(value)) {
54142
+ result = result.concat(value);
54143
+ } else if (value instanceof Document) {
54144
+ result.push(value);
54145
+ }
54146
+ }
54147
+ return result;
54148
+ };
54149
+
53926
54150
  /**
53927
54151
  * Explicitly executes population and returns a promise. Useful for promises integration.
53928
54152
  *
@@ -53992,25 +54216,21 @@ Document.prototype.execPopulate = function(callback) {
53992
54216
 
53993
54217
  Document.prototype.populated = function(path, val, options) {
53994
54218
  // val and options are internal
53995
- if (val === null || val === void 0) {
54219
+ if (val == null || val === true) {
53996
54220
  if (!this.$__.populated) {
53997
54221
  return undefined;
53998
54222
  }
53999
- const v = this.$__.populated[path];
54223
+
54224
+ // Map paths can be populated with either `path.$*` or just `path`
54225
+ const _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path;
54226
+
54227
+ const v = this.$__.populated[_path];
54000
54228
  if (v) {
54001
- return v.value;
54229
+ return val === true ? v : v.value;
54002
54230
  }
54003
54231
  return undefined;
54004
54232
  }
54005
54233
 
54006
- // internal
54007
- if (val === true) {
54008
- if (!this.$__.populated) {
54009
- return undefined;
54010
- }
54011
- return this.$__.populated[path];
54012
- }
54013
-
54014
54234
  this.$__.populated || (this.$__.populated = {});
54015
54235
  this.$__.populated[path] = { value: val, options: options };
54016
54236
 
@@ -54043,7 +54263,7 @@ Document.prototype.populated = function(path, val, options) {
54043
54263
  * console.log(doc.author); // '5144cf8050f071d979c118a7'
54044
54264
  * })
54045
54265
  *
54046
- * If the path was not populated, this is a no-op.
54266
+ * If the path was not provided, then all populated fields are returned to their unpopulated state.
54047
54267
  *
54048
54268
  * @param {String} path
54049
54269
  * @return {Document} this
@@ -54078,7 +54298,7 @@ Document.prototype.depopulate = function(path) {
54078
54298
  continue;
54079
54299
  }
54080
54300
  delete populated[key];
54081
- this.$set(key, populatedIds);
54301
+ utils.setValue(key, populatedIds, this._doc);
54082
54302
  }
54083
54303
  return this;
54084
54304
  }
@@ -54091,7 +54311,7 @@ Document.prototype.depopulate = function(path) {
54091
54311
  delete this.$$populatedVirtuals[singlePath];
54092
54312
  delete this._doc[singlePath];
54093
54313
  } else if (populatedIds) {
54094
- this.$set(singlePath, populatedIds);
54314
+ utils.setValue(singlePath, populatedIds, this._doc);
54095
54315
  }
54096
54316
  }
54097
54317
  return this;
@@ -54168,8 +54388,8 @@ Document.prototype.getChanges = function() {
54168
54388
  Document.ValidationError = ValidationError;
54169
54389
  module.exports = exports = Document;
54170
54390
 
54171
- }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process'))
54172
- },{"../../is-buffer/index.js":178,"./error/index":203,"./error/objectExpected":208,"./error/objectParameter":209,"./error/parallelValidate":212,"./error/strict":213,"./error/validation":214,"./error/validator":215,"./helpers/common":219,"./helpers/document/cleanModifiedSubpaths":224,"./helpers/document/compile":225,"./helpers/document/getEmbeddedDiscriminatorPath":226,"./helpers/document/handleSpreadDoc":227,"./helpers/get":228,"./helpers/isPromise":234,"./helpers/projection/isDefiningProjection":238,"./helpers/projection/isExclusive":239,"./helpers/promiseOrCallback":240,"./helpers/symbols":251,"./internal":255,"./options":256,"./plugins/idGetter":270,"./queryhelpers":272,"./schema":273,"./schema/mixed":283,"./types/array":296,"./types/documentarray":300,"./types/embedded":301,"./utils":306,"./virtualtype":307,"_process":324,"events":176,"mpath":309,"util":331}],194:[function(require,module,exports){
54391
+ }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
54392
+ },{"../../is-buffer/index.js":178,"./error/index":203,"./error/objectExpected":208,"./error/objectParameter":209,"./error/parallelValidate":212,"./error/strict":213,"./error/validation":214,"./error/validator":215,"./helpers/common":219,"./helpers/document/cleanModifiedSubpaths":225,"./helpers/document/compile":226,"./helpers/document/getEmbeddedDiscriminatorPath":227,"./helpers/document/handleSpreadDoc":228,"./helpers/get":229,"./helpers/immediate":232,"./helpers/isPromise":236,"./helpers/projection/isDefiningProjection":240,"./helpers/projection/isExclusive":241,"./helpers/promiseOrCallback":242,"./helpers/symbols":253,"./internal":257,"./options":258,"./plugins/idGetter":272,"./queryhelpers":274,"./schema":275,"./schema/mixed":285,"./schema/symbols":295,"./types/array":298,"./types/documentarray":302,"./types/embedded":303,"./utils":308,"./virtualtype":309,"events":176,"mpath":311,"util":333}],194:[function(require,module,exports){
54173
54393
  'use strict';
54174
54394
 
54175
54395
  /* eslint-env browser */
@@ -54263,6 +54483,9 @@ exports.Binary = require('./binary');
54263
54483
  exports.Collection = function() {
54264
54484
  throw new Error('Cannot create a collection from browser library');
54265
54485
  };
54486
+ exports.getConnection = () => function() {
54487
+ throw new Error('Cannot create a connection from browser library');
54488
+ };
54266
54489
  exports.Decimal128 = require('./decimal128');
54267
54490
  exports.ObjectId = require('./objectid');
54268
54491
  exports.ReadPreference = require('./ReadPreference');
@@ -54322,8 +54545,9 @@ class CastError extends MongooseError {
54322
54545
  // If no args, assume we'll `init()` later.
54323
54546
  if (arguments.length > 0) {
54324
54547
  const stringValue = getStringValue(value);
54548
+ const valueType = getValueType(value);
54325
54549
  const messageFormat = getMessageFormat(schemaType);
54326
- const msg = formatMessage(null, type, stringValue, path, messageFormat);
54550
+ const msg = formatMessage(null, type, stringValue, path, messageFormat, valueType);
54327
54551
  super(msg);
54328
54552
  this.init(type, value, path, reason, schemaType);
54329
54553
  } else {
@@ -54331,6 +54555,18 @@ class CastError extends MongooseError {
54331
54555
  }
54332
54556
  }
54333
54557
 
54558
+ toJSON() {
54559
+ return {
54560
+ stringValue: this.stringValue,
54561
+ valueType: this.valueType,
54562
+ kind: this.kind,
54563
+ value: this.value,
54564
+ path: this.path,
54565
+ reason: this.reason,
54566
+ name: this.name,
54567
+ message: this.message
54568
+ };
54569
+ }
54334
54570
  /*!
54335
54571
  * ignore
54336
54572
  */
@@ -54341,6 +54577,7 @@ class CastError extends MongooseError {
54341
54577
  this.value = value;
54342
54578
  this.path = path;
54343
54579
  this.reason = reason;
54580
+ this.valueType = getValueType(value);
54344
54581
  }
54345
54582
 
54346
54583
  /*!
@@ -54355,6 +54592,7 @@ class CastError extends MongooseError {
54355
54592
  this.path = other.path;
54356
54593
  this.reason = other.reason;
54357
54594
  this.message = other.message;
54595
+ this.valueType = other.valueType;
54358
54596
  }
54359
54597
 
54360
54598
  /*!
@@ -54363,7 +54601,7 @@ class CastError extends MongooseError {
54363
54601
  setModel(model) {
54364
54602
  this.model = model;
54365
54603
  this.message = formatMessage(model, this.kind, this.stringValue, this.path,
54366
- this.messageFormat);
54604
+ this.messageFormat, this.valueType);
54367
54605
  }
54368
54606
  }
54369
54607
 
@@ -54380,6 +54618,21 @@ function getStringValue(value) {
54380
54618
  return stringValue;
54381
54619
  }
54382
54620
 
54621
+ function getValueType(value) {
54622
+ if (value == null) {
54623
+ return '' + value;
54624
+ }
54625
+
54626
+ const t = typeof value;
54627
+ if (t !== 'object') {
54628
+ return t;
54629
+ }
54630
+ if (typeof value.constructor !== 'function') {
54631
+ return t;
54632
+ }
54633
+ return value.constructor.name;
54634
+ }
54635
+
54383
54636
  function getMessageFormat(schemaType) {
54384
54637
  const messageFormat = get(schemaType, 'options.cast', null);
54385
54638
  if (typeof messageFormat === 'string') {
@@ -54391,7 +54644,7 @@ function getMessageFormat(schemaType) {
54391
54644
  * ignore
54392
54645
  */
54393
54646
 
54394
- function formatMessage(model, kind, stringValue, path, messageFormat) {
54647
+ function formatMessage(model, kind, stringValue, path, messageFormat, valueType) {
54395
54648
  if (messageFormat != null) {
54396
54649
  let ret = messageFormat.
54397
54650
  replace('{KIND}', kind).
@@ -54403,12 +54656,12 @@ function formatMessage(model, kind, stringValue, path, messageFormat) {
54403
54656
 
54404
54657
  return ret;
54405
54658
  } else {
54659
+ const valueTypeMsg = valueType ? ' (type ' + valueType + ')' : '';
54406
54660
  let ret = 'Cast to ' + kind + ' failed for value ' +
54407
- stringValue + ' at path "' + path + '"';
54661
+ stringValue + valueTypeMsg + ' at path "' + path + '"';
54408
54662
  if (model != null) {
54409
54663
  ret += ' for model "' + model.modelName + '"';
54410
54664
  }
54411
-
54412
54665
  return ret;
54413
54666
  }
54414
54667
  }
@@ -54419,7 +54672,7 @@ function formatMessage(model, kind, stringValue, path, messageFormat) {
54419
54672
 
54420
54673
  module.exports = CastError;
54421
54674
 
54422
- },{"../helpers/get":228,"./mongooseError":206,"util":331}],202:[function(require,module,exports){
54675
+ },{"../helpers/get":229,"./mongooseError":206,"util":333}],202:[function(require,module,exports){
54423
54676
 
54424
54677
  /*!
54425
54678
  * Module dependencies.
@@ -54807,7 +55060,7 @@ Object.defineProperty(DocumentNotFoundError.prototype, 'name', {
54807
55060
 
54808
55061
  module.exports = DocumentNotFoundError;
54809
55062
 
54810
- },{"./":203,"util":331}],208:[function(require,module,exports){
55063
+ },{"./":203,"util":333}],208:[function(require,module,exports){
54811
55064
  /*!
54812
55065
  * Module dependencies.
54813
55066
  */
@@ -55009,6 +55262,7 @@ module.exports = StrictModeError;
55009
55262
  'use strict';
55010
55263
 
55011
55264
  const MongooseError = require('./mongooseError');
55265
+ const getConstructorName = require('../helpers/getConstructorName');
55012
55266
  const util = require('util');
55013
55267
 
55014
55268
  class ValidationError extends MongooseError {
@@ -55021,7 +55275,7 @@ class ValidationError extends MongooseError {
55021
55275
  */
55022
55276
  constructor(instance) {
55023
55277
  let _message;
55024
- if (instance && instance.constructor.name === 'model') {
55278
+ if (getConstructorName(instance) === 'model') {
55025
55279
  _message = instance.constructor.modelName + ' validation failed';
55026
55280
  } else {
55027
55281
  _message = 'Validation failed';
@@ -55114,7 +55368,7 @@ function _generateMessage(err) {
55114
55368
 
55115
55369
  module.exports = ValidationError;
55116
55370
 
55117
- },{"./mongooseError":206,"util":331}],215:[function(require,module,exports){
55371
+ },{"../helpers/getConstructorName":230,"./mongooseError":206,"util":333}],215:[function(require,module,exports){
55118
55372
  /*!
55119
55373
  * Module dependencies.
55120
55374
  */
@@ -55260,6 +55514,9 @@ function arrayDepth(arr) {
55260
55514
  if (arr.length === 0) {
55261
55515
  return { min: 1, max: 1, containsNonArrayItem: false };
55262
55516
  }
55517
+ if (arr.length === 1 && !Array.isArray(arr[0])) {
55518
+ return { min: 1, max: 1, containsNonArrayItem: false };
55519
+ }
55263
55520
 
55264
55521
  const res = arrayDepth(arr[0]);
55265
55522
 
@@ -55423,7 +55680,7 @@ function cloneArray(arr, options) {
55423
55680
 
55424
55681
  return ret;
55425
55682
  }
55426
- },{"../types/decimal128":299,"../types/objectid":304,"../utils":306,"./getFunctionName":229,"./isBsonType":231,"./isMongooseObject":232,"./isObject":233,"./specialProperties":250,"./symbols":251,"regexp-clone":325}],219:[function(require,module,exports){
55683
+ },{"../types/decimal128":301,"../types/objectid":306,"../utils":308,"./getFunctionName":231,"./isBsonType":233,"./isMongooseObject":234,"./isObject":235,"./specialProperties":252,"./symbols":253,"regexp-clone":327}],219:[function(require,module,exports){
55427
55684
  (function (Buffer){(function (){
55428
55685
  'use strict';
55429
55686
 
@@ -55533,7 +55790,24 @@ function shouldFlatten(val) {
55533
55790
  }
55534
55791
 
55535
55792
  }).call(this)}).call(this,require("buffer").Buffer)
55536
- },{"../driver":195,"../types/decimal128":299,"../types/objectid":304,"./isMongooseObject":232,"buffer":128}],220:[function(require,module,exports){
55793
+ },{"../driver":195,"../types/decimal128":301,"../types/objectid":306,"./isMongooseObject":234,"buffer":128}],220:[function(require,module,exports){
55794
+ 'use strict';
55795
+
55796
+ const ObjectId = require('../../types/objectid');
55797
+
55798
+ module.exports = function areDiscriminatorValuesEqual(a, b) {
55799
+ if (typeof a === 'string' && typeof b === 'string') {
55800
+ return a === b;
55801
+ }
55802
+ if (typeof a === 'number' && typeof b === 'number') {
55803
+ return a === b;
55804
+ }
55805
+ if (a instanceof ObjectId && b instanceof ObjectId) {
55806
+ return a.toString() === b.toString();
55807
+ }
55808
+ return false;
55809
+ };
55810
+ },{"../../types/objectid":306}],221:[function(require,module,exports){
55537
55811
  'use strict';
55538
55812
 
55539
55813
  module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) {
@@ -55546,7 +55820,7 @@ module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection
55546
55820
  selected.splice(selected.indexOf(_discriminatorKey), 1);
55547
55821
  }
55548
55822
  };
55549
- },{}],221:[function(require,module,exports){
55823
+ },{}],222:[function(require,module,exports){
55550
55824
  'use strict';
55551
55825
 
55552
55826
  const getDiscriminatorByValue = require('./getDiscriminatorByValue');
@@ -55563,7 +55837,7 @@ module.exports = function getConstructor(Constructor, value) {
55563
55837
  if (Constructor.discriminators[value[discriminatorKey]]) {
55564
55838
  Constructor = Constructor.discriminators[value[discriminatorKey]];
55565
55839
  } else {
55566
- const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]);
55840
+ const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[discriminatorKey]);
55567
55841
  if (constructorByValue) {
55568
55842
  Constructor = constructorByValue;
55569
55843
  }
@@ -55572,9 +55846,11 @@ module.exports = function getConstructor(Constructor, value) {
55572
55846
 
55573
55847
  return Constructor;
55574
55848
  };
55575
- },{"./getDiscriminatorByValue":222}],222:[function(require,module,exports){
55849
+ },{"./getDiscriminatorByValue":223}],223:[function(require,module,exports){
55576
55850
  'use strict';
55577
55851
 
55852
+ const areDiscriminatorValuesEqual = require('./areDiscriminatorValuesEqual');
55853
+
55578
55854
  /*!
55579
55855
  * returns discriminator by discriminatorMapping.value
55580
55856
  *
@@ -55582,27 +55858,27 @@ module.exports = function getConstructor(Constructor, value) {
55582
55858
  * @param {string} value
55583
55859
  */
55584
55860
 
55585
- module.exports = function getDiscriminatorByValue(model, value) {
55586
- let discriminator = null;
55587
- if (!model.discriminators) {
55588
- return discriminator;
55861
+ module.exports = function getDiscriminatorByValue(discriminators, value) {
55862
+ if (discriminators == null) {
55863
+ return null;
55589
55864
  }
55590
- for (const name in model.discriminators) {
55591
- const it = model.discriminators[name];
55865
+ for (const name of Object.keys(discriminators)) {
55866
+ const it = discriminators[name];
55592
55867
  if (
55593
55868
  it.schema &&
55594
55869
  it.schema.discriminatorMapping &&
55595
- it.schema.discriminatorMapping.value == value
55870
+ areDiscriminatorValuesEqual(it.schema.discriminatorMapping.value, value)
55596
55871
  ) {
55597
- discriminator = it;
55598
- break;
55872
+ return it;
55599
55873
  }
55600
55874
  }
55601
- return discriminator;
55875
+ return null;
55602
55876
  };
55603
- },{}],223:[function(require,module,exports){
55877
+ },{"./areDiscriminatorValuesEqual":220}],224:[function(require,module,exports){
55604
55878
  'use strict';
55605
55879
 
55880
+ const areDiscriminatorValuesEqual = require('./areDiscriminatorValuesEqual');
55881
+
55606
55882
  /*!
55607
55883
  * returns discriminator by discriminatorMapping.value
55608
55884
  *
@@ -55619,13 +55895,13 @@ module.exports = function getSchemaDiscriminatorByValue(schema, value) {
55619
55895
  if (discriminatorSchema.discriminatorMapping == null) {
55620
55896
  continue;
55621
55897
  }
55622
- if (discriminatorSchema.discriminatorMapping.value === value) {
55898
+ if (areDiscriminatorValuesEqual(discriminatorSchema.discriminatorMapping.value, value)) {
55623
55899
  return discriminatorSchema;
55624
55900
  }
55625
55901
  }
55626
55902
  return null;
55627
55903
  };
55628
- },{}],224:[function(require,module,exports){
55904
+ },{"./areDiscriminatorValuesEqual":220}],225:[function(require,module,exports){
55629
55905
  'use strict';
55630
55906
 
55631
55907
  /*!
@@ -55642,7 +55918,7 @@ module.exports = function cleanModifiedSubpaths(doc, path, options) {
55642
55918
  }
55643
55919
  for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) {
55644
55920
  if (skipDocArrays) {
55645
- const schemaType = doc.schema.path(modifiedPath);
55921
+ const schemaType = doc.$__schema.path(modifiedPath);
55646
55922
  if (schemaType && schemaType.$isMongooseDocumentArray) {
55647
55923
  continue;
55648
55924
  }
@@ -55655,7 +55931,7 @@ module.exports = function cleanModifiedSubpaths(doc, path, options) {
55655
55931
  return deleted;
55656
55932
  };
55657
55933
 
55658
- },{}],225:[function(require,module,exports){
55934
+ },{}],226:[function(require,module,exports){
55659
55935
  'use strict';
55660
55936
 
55661
55937
  const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol;
@@ -55732,6 +56008,13 @@ function defineKey(prop, subprops, prototype, prefix, keys, options) {
55732
56008
  value: prototype.schema
55733
56009
  });
55734
56010
 
56011
+ Object.defineProperty(nested, '$__schema', {
56012
+ enumerable: false,
56013
+ configurable: true,
56014
+ writable: false,
56015
+ value: prototype.schema
56016
+ });
56017
+
55735
56018
  Object.defineProperty(nested, documentSchemaSymbol, {
55736
56019
  enumerable: false,
55737
56020
  configurable: true,
@@ -55839,13 +56122,7 @@ function getOwnPropertyDescriptors(object) {
55839
56122
  const result = {};
55840
56123
 
55841
56124
  Object.getOwnPropertyNames(object).forEach(function(key) {
55842
- result[key] = Object.getOwnPropertyDescriptor(object, key);
55843
- // Assume these are schema paths, ignore them re: #5470
55844
- if (result[key].get) {
55845
- delete result[key];
55846
- return;
55847
- }
55848
- result[key].enumerable = [
56125
+ const skip = [
55849
56126
  'isNew',
55850
56127
  '$__',
55851
56128
  'errors',
@@ -55856,12 +56133,18 @@ function getOwnPropertyDescriptors(object) {
55856
56133
  '__index',
55857
56134
  '$isDocumentArrayElement'
55858
56135
  ].indexOf(key) === -1;
56136
+ if (skip) {
56137
+ return;
56138
+ }
56139
+
56140
+ result[key] = Object.getOwnPropertyDescriptor(object, key);
56141
+ result[key].enumerable = false;
55859
56142
  });
55860
56143
 
55861
56144
  return result;
55862
56145
  }
55863
56146
 
55864
- },{"../../document":193,"../../helpers/get":228,"../../helpers/symbols":251,"../../options":256,"../../utils":306}],226:[function(require,module,exports){
56147
+ },{"../../document":193,"../../helpers/get":229,"../../helpers/symbols":253,"../../options":258,"../../utils":308}],227:[function(require,module,exports){
55865
56148
  'use strict';
55866
56149
 
55867
56150
  const get = require('../get');
@@ -55906,7 +56189,7 @@ module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) {
55906
56189
  return typeOnly ? type : schema;
55907
56190
  };
55908
56191
 
55909
- },{"../get":228}],227:[function(require,module,exports){
56192
+ },{"../get":229}],228:[function(require,module,exports){
55910
56193
  'use strict';
55911
56194
 
55912
56195
  const utils = require('../../utils');
@@ -55924,7 +56207,7 @@ module.exports = function handleSpreadDoc(v) {
55924
56207
 
55925
56208
  return v;
55926
56209
  };
55927
- },{"../../utils":306}],228:[function(require,module,exports){
56210
+ },{"../../utils":308}],229:[function(require,module,exports){
55928
56211
  'use strict';
55929
56212
 
55930
56213
  /*!
@@ -55933,7 +56216,30 @@ module.exports = function handleSpreadDoc(v) {
55933
56216
  */
55934
56217
 
55935
56218
  module.exports = function get(obj, path, def) {
55936
- const parts = path.split('.');
56219
+ let parts;
56220
+ let isPathArray = false;
56221
+ if (typeof path === 'string') {
56222
+ if (path.indexOf('.') === -1) {
56223
+ const _v = getProperty(obj, path);
56224
+ if (_v == null) {
56225
+ return def;
56226
+ }
56227
+ return _v;
56228
+ }
56229
+
56230
+ parts = path.split('.');
56231
+ } else {
56232
+ isPathArray = true;
56233
+ parts = path;
56234
+
56235
+ if (parts.length === 1) {
56236
+ const _v = getProperty(obj, parts[0]);
56237
+ if (_v == null) {
56238
+ return def;
56239
+ }
56240
+ return _v;
56241
+ }
56242
+ }
55937
56243
  let rest = path;
55938
56244
  let cur = obj;
55939
56245
  for (const part of parts) {
@@ -55943,13 +56249,15 @@ module.exports = function get(obj, path, def) {
55943
56249
 
55944
56250
  // `lib/cast.js` depends on being able to get dotted paths in updates,
55945
56251
  // like `{ $set: { 'a.b': 42 } }`
55946
- if (cur[rest] != null) {
56252
+ if (!isPathArray && cur[rest] != null) {
55947
56253
  return cur[rest];
55948
56254
  }
55949
56255
 
55950
56256
  cur = getProperty(cur, part);
55951
56257
 
55952
- rest = rest.substr(part.length + 1);
56258
+ if (!isPathArray) {
56259
+ rest = rest.substr(part.length + 1);
56260
+ }
55953
56261
  }
55954
56262
 
55955
56263
  return cur == null ? def : cur;
@@ -55964,7 +56272,23 @@ function getProperty(obj, prop) {
55964
56272
  }
55965
56273
  return obj[prop];
55966
56274
  }
55967
- },{}],229:[function(require,module,exports){
56275
+ },{}],230:[function(require,module,exports){
56276
+ 'use strict';
56277
+
56278
+ /*!
56279
+ * If `val` is an object, returns constructor name, if possible. Otherwise returns undefined.
56280
+ */
56281
+
56282
+ module.exports = function getConstructorName(val) {
56283
+ if (val == null) {
56284
+ return void 0;
56285
+ }
56286
+ if (typeof val.constructor !== 'function') {
56287
+ return void 0;
56288
+ }
56289
+ return val.constructor.name;
56290
+ };
56291
+ },{}],231:[function(require,module,exports){
55968
56292
  'use strict';
55969
56293
 
55970
56294
  module.exports = function(fn) {
@@ -55974,7 +56298,7 @@ module.exports = function(fn) {
55974
56298
  return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
55975
56299
  };
55976
56300
 
55977
- },{}],230:[function(require,module,exports){
56301
+ },{}],232:[function(require,module,exports){
55978
56302
  (function (process){(function (){
55979
56303
  /*!
55980
56304
  * Centralize this so we can more easily work around issues with people
@@ -55985,12 +56309,14 @@ module.exports = function(fn) {
55985
56309
 
55986
56310
  'use strict';
55987
56311
 
56312
+ const nextTick = process.nextTick.bind(process);
56313
+
55988
56314
  module.exports = function immediate(cb) {
55989
- return process.nextTick(cb);
56315
+ return nextTick(cb);
55990
56316
  };
55991
56317
 
55992
56318
  }).call(this)}).call(this,require('_process'))
55993
- },{"_process":324}],231:[function(require,module,exports){
56319
+ },{"_process":326}],233:[function(require,module,exports){
55994
56320
  'use strict';
55995
56321
 
55996
56322
  const get = require('./get');
@@ -56005,7 +56331,7 @@ function isBsonType(obj, typename) {
56005
56331
 
56006
56332
  module.exports = isBsonType;
56007
56333
 
56008
- },{"./get":228}],232:[function(require,module,exports){
56334
+ },{"./get":229}],234:[function(require,module,exports){
56009
56335
  'use strict';
56010
56336
 
56011
56337
  /*!
@@ -56027,7 +56353,7 @@ module.exports = function(v) {
56027
56353
  v.isMongooseBuffer || // Buffer
56028
56354
  v.$isMongooseMap; // Map
56029
56355
  };
56030
- },{}],233:[function(require,module,exports){
56356
+ },{}],235:[function(require,module,exports){
56031
56357
  (function (Buffer){(function (){
56032
56358
  'use strict';
56033
56359
 
@@ -56046,14 +56372,14 @@ module.exports = function(arg) {
56046
56372
  return Object.prototype.toString.call(arg) === '[object Object]';
56047
56373
  };
56048
56374
  }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
56049
- },{"../../../is-buffer/index.js":178}],234:[function(require,module,exports){
56375
+ },{"../../../is-buffer/index.js":178}],236:[function(require,module,exports){
56050
56376
  'use strict';
56051
56377
  function isPromise(val) {
56052
56378
  return !!val && (typeof val === 'object' || typeof val === 'function') && typeof val.then === 'function';
56053
56379
  }
56054
56380
 
56055
56381
  module.exports = isPromise;
56056
- },{}],235:[function(require,module,exports){
56382
+ },{}],237:[function(require,module,exports){
56057
56383
  'use strict';
56058
56384
 
56059
56385
  const symbols = require('../../schema/symbols');
@@ -56192,7 +56518,7 @@ function applyHooks(model, schema, options) {
56192
56518
  createWrapper(method, originalMethod, null, customMethodOptions);
56193
56519
  }
56194
56520
  }
56195
- },{"../../schema/symbols":293,"../promiseOrCallback":240}],236:[function(require,module,exports){
56521
+ },{"../../schema/symbols":295,"../promiseOrCallback":242}],238:[function(require,module,exports){
56196
56522
  'use strict';
56197
56523
 
56198
56524
  const Mixed = require('../../schema/mixed');
@@ -56258,7 +56584,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
56258
56584
  }
56259
56585
 
56260
56586
  let value = name;
56261
- if (typeof tiedValue == 'string' && tiedValue.length) {
56587
+ if ((typeof tiedValue === 'string' && tiedValue.length) || tiedValue != null) {
56262
56588
  value = tiedValue;
56263
56589
  }
56264
56590
 
@@ -56321,17 +56647,17 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
56321
56647
  default: value,
56322
56648
  select: true,
56323
56649
  set: function(newName) {
56324
- if (newName === value) {
56650
+ if (newName === value || (Array.isArray(value) && utils.deepEqual(newName, value))) {
56325
56651
  return value;
56326
56652
  }
56327
56653
  throw new Error('Can\'t set discriminator key "' + key + '"');
56328
56654
  },
56329
56655
  $skipDiscriminatorCheck: true
56330
56656
  };
56331
- obj[key][schema.options.typeKey] = existingPath ?
56332
- existingPath.instance :
56333
- String;
56657
+ obj[key][schema.options.typeKey] = existingPath ? existingPath.options[schema.options.typeKey] : String;
56334
56658
  schema.add(obj);
56659
+
56660
+
56335
56661
  schema.discriminatorMapping = { key: key, value: value, isRoot: false };
56336
56662
 
56337
56663
  if (baseSchema.options.collection) {
@@ -56399,7 +56725,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
56399
56725
  return schema;
56400
56726
  };
56401
56727
 
56402
- },{"../../schema/mixed":283,"../../utils":306,"../document/compile":225,"../get":228}],237:[function(require,module,exports){
56728
+ },{"../../schema/mixed":285,"../../utils":308,"../document/compile":226,"../get":229}],239:[function(require,module,exports){
56403
56729
  'use strict';
56404
56730
 
56405
56731
  const MongooseError = require('../../error/mongooseError');
@@ -56419,7 +56745,7 @@ function validateRef(ref, path) {
56419
56745
  throw new MongooseError('Invalid ref at path "' + path + '". Got ' +
56420
56746
  util.inspect(ref, { depth: 0 }));
56421
56747
  }
56422
- },{"../../error/mongooseError":206,"util":331}],238:[function(require,module,exports){
56748
+ },{"../../error/mongooseError":206,"util":333}],240:[function(require,module,exports){
56423
56749
  'use strict';
56424
56750
 
56425
56751
  /*!
@@ -56439,7 +56765,7 @@ module.exports = function isDefiningProjection(val) {
56439
56765
  return true;
56440
56766
  };
56441
56767
 
56442
- },{}],239:[function(require,module,exports){
56768
+ },{}],241:[function(require,module,exports){
56443
56769
  'use strict';
56444
56770
 
56445
56771
  const isDefiningProjection = require('./isDefiningProjection');
@@ -56449,6 +56775,10 @@ const isDefiningProjection = require('./isDefiningProjection');
56449
56775
  */
56450
56776
 
56451
56777
  module.exports = function isExclusive(projection) {
56778
+ if (projection == null) {
56779
+ return null;
56780
+ }
56781
+
56452
56782
  const keys = Object.keys(projection);
56453
56783
  let ki = keys.length;
56454
56784
  let exclude = null;
@@ -56469,26 +56799,26 @@ module.exports = function isExclusive(projection) {
56469
56799
  return exclude;
56470
56800
  };
56471
56801
 
56472
- },{"./isDefiningProjection":238}],240:[function(require,module,exports){
56473
- (function (process){(function (){
56802
+ },{"./isDefiningProjection":240}],242:[function(require,module,exports){
56474
56803
  'use strict';
56475
56804
 
56476
56805
  const PromiseProvider = require('../promise_provider');
56806
+ const immediate = require('./immediate');
56477
56807
 
56478
- const emittedSymbol = Symbol.for('mongoose:emitted');
56808
+ const emittedSymbol = Symbol('mongoose:emitted');
56479
56809
 
56480
56810
  module.exports = function promiseOrCallback(callback, fn, ee, Promise) {
56481
56811
  if (typeof callback === 'function') {
56482
56812
  return fn(function(error) {
56483
56813
  if (error != null) {
56484
- if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
56814
+ if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
56485
56815
  error[emittedSymbol] = true;
56486
56816
  ee.emit('error', error);
56487
56817
  }
56488
56818
  try {
56489
56819
  callback(error);
56490
56820
  } catch (error) {
56491
- return process.nextTick(() => {
56821
+ return immediate(() => {
56492
56822
  throw error;
56493
56823
  });
56494
56824
  }
@@ -56503,7 +56833,7 @@ module.exports = function promiseOrCallback(callback, fn, ee, Promise) {
56503
56833
  return new Promise((resolve, reject) => {
56504
56834
  fn(function(error, res) {
56505
56835
  if (error != null) {
56506
- if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
56836
+ if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
56507
56837
  error[emittedSymbol] = true;
56508
56838
  ee.emit('error', error);
56509
56839
  }
@@ -56516,8 +56846,8 @@ module.exports = function promiseOrCallback(callback, fn, ee, Promise) {
56516
56846
  });
56517
56847
  });
56518
56848
  };
56519
- }).call(this)}).call(this,require('_process'))
56520
- },{"../promise_provider":271,"_process":324}],241:[function(require,module,exports){
56849
+
56850
+ },{"../promise_provider":273,"./immediate":232}],243:[function(require,module,exports){
56521
56851
  'use strict';
56522
56852
 
56523
56853
  /*!
@@ -56611,7 +56941,7 @@ function _getContexts(hook) {
56611
56941
  }
56612
56942
  return ret;
56613
56943
  }
56614
- },{}],242:[function(require,module,exports){
56944
+ },{}],244:[function(require,module,exports){
56615
56945
  'use strict';
56616
56946
 
56617
56947
  const specialKeys = new Set([
@@ -56623,7 +56953,7 @@ const specialKeys = new Set([
56623
56953
  module.exports = function isOperator(path) {
56624
56954
  return path.startsWith('$') && !specialKeys.has(path);
56625
56955
  };
56626
- },{}],243:[function(require,module,exports){
56956
+ },{}],245:[function(require,module,exports){
56627
56957
  'use strict';
56628
56958
 
56629
56959
  module.exports = function addAutoId(schema) {
@@ -56631,7 +56961,7 @@ module.exports = function addAutoId(schema) {
56631
56961
  _obj._id[schema.options.typeKey] = 'ObjectId';
56632
56962
  schema.add(_obj);
56633
56963
  };
56634
- },{}],244:[function(require,module,exports){
56964
+ },{}],246:[function(require,module,exports){
56635
56965
  'use strict';
56636
56966
 
56637
56967
  /**
@@ -56644,7 +56974,7 @@ module.exports = function cleanPositionalOperators(path) {
56644
56974
  replace(/\.\$(\[[^\]]*\])?(?=\.)/g, '.0').
56645
56975
  replace(/\.\$(\[[^\]]*\])?$/g, '.0');
56646
56976
  };
56647
- },{}],245:[function(require,module,exports){
56977
+ },{}],247:[function(require,module,exports){
56648
56978
  'use strict';
56649
56979
 
56650
56980
  const get = require('../get');
@@ -56801,7 +57131,7 @@ module.exports = function getIndexes(schema) {
56801
57131
  }
56802
57132
  };
56803
57133
 
56804
- },{"../get":228,"../isObject":233}],246:[function(require,module,exports){
57134
+ },{"../get":229,"../isObject":235}],248:[function(require,module,exports){
56805
57135
  'use strict';
56806
57136
 
56807
57137
  const addAutoId = require('./addAutoId');
@@ -56822,7 +57152,7 @@ module.exports = function handleIdOption(schema, options) {
56822
57152
 
56823
57153
  return schema;
56824
57154
  };
56825
- },{"./addAutoId":243}],247:[function(require,module,exports){
57155
+ },{"./addAutoId":245}],249:[function(require,module,exports){
56826
57156
  'use strict';
56827
57157
 
56828
57158
  module.exports = handleTimestampOption;
@@ -56847,11 +57177,19 @@ function handleTimestampOption(arg, prop) {
56847
57177
  }
56848
57178
  return arg[prop];
56849
57179
  }
56850
- },{}],248:[function(require,module,exports){
57180
+ },{}],250:[function(require,module,exports){
56851
57181
  'use strict';
56852
57182
 
56853
- module.exports = function merge(s1, s2) {
56854
- s1.add(s2.tree || {});
57183
+ module.exports = function merge(s1, s2, skipConflictingPaths) {
57184
+ const paths = Object.keys(s2.tree);
57185
+ const pathsToAdd = {};
57186
+ for (const key of paths) {
57187
+ if (skipConflictingPaths && (s1.paths[key] || s1.nested[key] || s1.singleNestedPaths[key])) {
57188
+ continue;
57189
+ }
57190
+ pathsToAdd[key] = s2.tree[key];
57191
+ }
57192
+ s1.add(pathsToAdd);
56855
57193
 
56856
57194
  s1.callQueue = s1.callQueue.concat(s2.callQueue);
56857
57195
  s1.method(s2.methods);
@@ -56868,7 +57206,7 @@ module.exports = function merge(s1, s2) {
56868
57206
  s1.s.hooks.merge(s2.s.hooks, false);
56869
57207
  };
56870
57208
 
56871
- },{}],249:[function(require,module,exports){
57209
+ },{}],251:[function(require,module,exports){
56872
57210
  'use strict';
56873
57211
 
56874
57212
  const StrictModeError = require('../../error/strict');
@@ -56915,11 +57253,11 @@ function createImmutableSetter(path, immutable) {
56915
57253
  };
56916
57254
  }
56917
57255
 
56918
- },{"../../error/strict":213}],250:[function(require,module,exports){
57256
+ },{"../../error/strict":213}],252:[function(require,module,exports){
56919
57257
  'use strict';
56920
57258
 
56921
57259
  module.exports = new Set(['__proto__', 'constructor', 'prototype']);
56922
- },{}],251:[function(require,module,exports){
57260
+ },{}],253:[function(require,module,exports){
56923
57261
  'use strict';
56924
57262
 
56925
57263
  exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics');
@@ -56939,7 +57277,7 @@ exports.schemaTypeSymbol = Symbol('mongoose#schemaType');
56939
57277
  exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments');
56940
57278
  exports.scopeSymbol = Symbol('mongoose#Document#scope');
56941
57279
  exports.validatorErrorSymbol = Symbol('mongoose:validatorError');
56942
- },{}],252:[function(require,module,exports){
57280
+ },{}],254:[function(require,module,exports){
56943
57281
  'use strict';
56944
57282
 
56945
57283
  const applyTimestampsToChildren = require('../update/applyTimestampsToChildren');
@@ -56993,7 +57331,7 @@ module.exports = function setupTimestamps(schema, timestamps) {
56993
57331
  (this.ownerDocument ? this.ownerDocument() : this).constructor.base.now();
56994
57332
  const auto_id = this._id && this._id.auto;
56995
57333
 
56996
- if (!skipCreatedAt && createdAt && !this.get(createdAt) && this.$__isSelected(createdAt)) {
57334
+ if (!skipCreatedAt && this.isNew && createdAt && !this.get(createdAt) && this.$__isSelected(createdAt)) {
56997
57335
  this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
56998
57336
  }
56999
57337
 
@@ -57051,7 +57389,7 @@ module.exports = function setupTimestamps(schema, timestamps) {
57051
57389
  next();
57052
57390
  }
57053
57391
  };
57054
- },{"../../schema/symbols":293,"../get":228,"../schema/handleTimestampOption":247,"../update/applyTimestampsToChildren":253,"../update/applyTimestampsToUpdate":254}],253:[function(require,module,exports){
57392
+ },{"../../schema/symbols":295,"../get":229,"../schema/handleTimestampOption":249,"../update/applyTimestampsToChildren":255,"../update/applyTimestampsToUpdate":256}],255:[function(require,module,exports){
57055
57393
  'use strict';
57056
57394
 
57057
57395
  const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
@@ -57073,34 +57411,10 @@ function applyTimestampsToChildren(now, update, schema) {
57073
57411
 
57074
57412
  if (hasDollarKey) {
57075
57413
  if (update.$push) {
57076
- for (const key of Object.keys(update.$push)) {
57077
- const $path = schema.path(key);
57078
- if (update.$push[key] &&
57079
- $path &&
57080
- $path.$isMongooseDocumentArray &&
57081
- $path.schema.options.timestamps) {
57082
- const timestamps = $path.schema.options.timestamps;
57083
- const createdAt = handleTimestampOption(timestamps, 'createdAt');
57084
- const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
57085
- if (update.$push[key].$each) {
57086
- update.$push[key].$each.forEach(function(subdoc) {
57087
- if (updatedAt != null) {
57088
- subdoc[updatedAt] = now;
57089
- }
57090
- if (createdAt != null) {
57091
- subdoc[createdAt] = now;
57092
- }
57093
- });
57094
- } else {
57095
- if (updatedAt != null) {
57096
- update.$push[key][updatedAt] = now;
57097
- }
57098
- if (createdAt != null) {
57099
- update.$push[key][createdAt] = now;
57100
- }
57101
- }
57102
- }
57103
- }
57414
+ _applyTimestampToUpdateOperator(update.$push);
57415
+ }
57416
+ if (update.$addToSet) {
57417
+ _applyTimestampToUpdateOperator(update.$addToSet);
57104
57418
  }
57105
57419
  if (update.$set != null) {
57106
57420
  const keys = Object.keys(update.$set);
@@ -57108,12 +57422,49 @@ function applyTimestampsToChildren(now, update, schema) {
57108
57422
  applyTimestampsToUpdateKey(schema, key, update.$set, now);
57109
57423
  }
57110
57424
  }
57425
+ if (update.$setOnInsert != null) {
57426
+ const keys = Object.keys(update.$setOnInsert);
57427
+ for (const key of keys) {
57428
+ applyTimestampsToUpdateKey(schema, key, update.$setOnInsert, now);
57429
+ }
57430
+ }
57111
57431
  }
57112
57432
 
57113
57433
  const updateKeys = Object.keys(update).filter(key => !key.startsWith('$'));
57114
57434
  for (const key of updateKeys) {
57115
57435
  applyTimestampsToUpdateKey(schema, key, update, now);
57116
57436
  }
57437
+
57438
+ function _applyTimestampToUpdateOperator(op) {
57439
+ for (const key of Object.keys(op)) {
57440
+ const $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, ''));
57441
+ if (op[key] &&
57442
+ $path &&
57443
+ $path.$isMongooseDocumentArray &&
57444
+ $path.schema.options.timestamps) {
57445
+ const timestamps = $path.schema.options.timestamps;
57446
+ const createdAt = handleTimestampOption(timestamps, 'createdAt');
57447
+ const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
57448
+ if (op[key].$each) {
57449
+ op[key].$each.forEach(function(subdoc) {
57450
+ if (updatedAt != null) {
57451
+ subdoc[updatedAt] = now;
57452
+ }
57453
+ if (createdAt != null) {
57454
+ subdoc[createdAt] = now;
57455
+ }
57456
+ });
57457
+ } else {
57458
+ if (updatedAt != null) {
57459
+ op[key][updatedAt] = now;
57460
+ }
57461
+ if (createdAt != null) {
57462
+ op[key][createdAt] = now;
57463
+ }
57464
+ }
57465
+ }
57466
+ }
57467
+ }
57117
57468
  }
57118
57469
 
57119
57470
  function applyTimestampsToDocumentArray(arr, schematype, now) {
@@ -57224,7 +57575,7 @@ function applyTimestampsToUpdateKey(schema, key, update, now) {
57224
57575
  }
57225
57576
  }
57226
57577
  }
57227
- },{"../schema/cleanPositionalOperators":244,"../schema/handleTimestampOption":247}],254:[function(require,module,exports){
57578
+ },{"../schema/cleanPositionalOperators":246,"../schema/handleTimestampOption":249}],256:[function(require,module,exports){
57228
57579
  'use strict';
57229
57580
 
57230
57581
  /*!
@@ -57345,7 +57696,7 @@ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, optio
57345
57696
  return updates;
57346
57697
  }
57347
57698
 
57348
- },{"../get":228}],255:[function(require,module,exports){
57699
+ },{"../get":229}],257:[function(require,module,exports){
57349
57700
  /*!
57350
57701
  * Dependencies
57351
57702
  */
@@ -57385,7 +57736,7 @@ function InternalCache() {
57385
57736
  this.fullPath = undefined;
57386
57737
  }
57387
57738
 
57388
- },{"./statemachine":295}],256:[function(require,module,exports){
57739
+ },{"./statemachine":297}],258:[function(require,module,exports){
57389
57740
  'use strict';
57390
57741
 
57391
57742
  /*!
@@ -57398,10 +57749,11 @@ exports.internalToObjectOptions = {
57398
57749
  getters: false,
57399
57750
  _skipDepopulateTopLevel: true,
57400
57751
  depopulate: true,
57401
- flattenDecimals: false
57752
+ flattenDecimals: false,
57753
+ useProjection: false
57402
57754
  };
57403
57755
 
57404
- },{}],257:[function(require,module,exports){
57756
+ },{}],259:[function(require,module,exports){
57405
57757
  'use strict';
57406
57758
 
57407
57759
  const clone = require('../helpers/clone');
@@ -57438,7 +57790,7 @@ class PopulateOptions {
57438
57790
  */
57439
57791
 
57440
57792
  module.exports = PopulateOptions;
57441
- },{"../helpers/clone":218}],258:[function(require,module,exports){
57793
+ },{"../helpers/clone":218}],260:[function(require,module,exports){
57442
57794
  'use strict';
57443
57795
 
57444
57796
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57491,14 +57843,14 @@ Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts);
57491
57843
  * @instance
57492
57844
  */
57493
57845
 
57494
- Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts);
57846
+ Object.defineProperty(SchemaArrayOptions.prototype, 'of', opts);
57495
57847
 
57496
57848
  /*!
57497
57849
  * ignore
57498
57850
  */
57499
57851
 
57500
57852
  module.exports = SchemaArrayOptions;
57501
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],259:[function(require,module,exports){
57853
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],261:[function(require,module,exports){
57502
57854
  'use strict';
57503
57855
 
57504
57856
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57537,7 +57889,7 @@ Object.defineProperty(SchemaBufferOptions.prototype, 'subtype', opts);
57537
57889
  */
57538
57890
 
57539
57891
  module.exports = SchemaBufferOptions;
57540
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],260:[function(require,module,exports){
57892
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],262:[function(require,module,exports){
57541
57893
  'use strict';
57542
57894
 
57543
57895
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57602,7 +57954,7 @@ Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts);
57602
57954
  */
57603
57955
 
57604
57956
  module.exports = SchemaDateOptions;
57605
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],261:[function(require,module,exports){
57957
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],263:[function(require,module,exports){
57606
57958
  'use strict';
57607
57959
 
57608
57960
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57671,7 +58023,7 @@ Object.defineProperty(SchemaDocumentArrayOptions.prototype, '_id', opts);
57671
58023
  */
57672
58024
 
57673
58025
  module.exports = SchemaDocumentArrayOptions;
57674
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],262:[function(require,module,exports){
58026
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],264:[function(require,module,exports){
57675
58027
  'use strict';
57676
58028
 
57677
58029
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57715,7 +58067,7 @@ const opts = require('./propertyOptions');
57715
58067
  Object.defineProperty(SchemaMapOptions.prototype, 'of', opts);
57716
58068
 
57717
58069
  module.exports = SchemaMapOptions;
57718
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],263:[function(require,module,exports){
58070
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],265:[function(require,module,exports){
57719
58071
  'use strict';
57720
58072
 
57721
58073
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57815,7 +58167,7 @@ Object.defineProperty(SchemaNumberOptions.prototype, 'populate', opts);
57815
58167
  */
57816
58168
 
57817
58169
  module.exports = SchemaNumberOptions;
57818
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],264:[function(require,module,exports){
58170
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],266:[function(require,module,exports){
57819
58171
  'use strict';
57820
58172
 
57821
58173
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57879,7 +58231,7 @@ Object.defineProperty(SchemaObjectIdOptions.prototype, 'populate', opts);
57879
58231
  */
57880
58232
 
57881
58233
  module.exports = SchemaObjectIdOptions;
57882
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],265:[function(require,module,exports){
58234
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],267:[function(require,module,exports){
57883
58235
  'use strict';
57884
58236
 
57885
58237
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -57922,7 +58274,7 @@ const opts = require('./propertyOptions');
57922
58274
  Object.defineProperty(SchemaSingleNestedOptions.prototype, '_id', opts);
57923
58275
 
57924
58276
  module.exports = SchemaSingleNestedOptions;
57925
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],266:[function(require,module,exports){
58277
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],268:[function(require,module,exports){
57926
58278
  'use strict';
57927
58279
 
57928
58280
  const SchemaTypeOptions = require('./SchemaTypeOptions');
@@ -58062,7 +58414,7 @@ Object.defineProperty(SchemaStringOptions.prototype, 'populate', opts);
58062
58414
 
58063
58415
  module.exports = SchemaStringOptions;
58064
58416
 
58065
- },{"./SchemaTypeOptions":267,"./propertyOptions":269}],267:[function(require,module,exports){
58417
+ },{"./SchemaTypeOptions":269,"./propertyOptions":271}],269:[function(require,module,exports){
58066
58418
  'use strict';
58067
58419
 
58068
58420
  const clone = require('../helpers/clone');
@@ -58294,7 +58646,7 @@ Object.defineProperty(SchemaTypeOptions.prototype, 'text', opts);
58294
58646
  Object.defineProperty(SchemaTypeOptions.prototype, 'transform', opts);
58295
58647
 
58296
58648
  module.exports = SchemaTypeOptions;
58297
- },{"../helpers/clone":218,"./propertyOptions":269}],268:[function(require,module,exports){
58649
+ },{"../helpers/clone":218,"./propertyOptions":271}],270:[function(require,module,exports){
58298
58650
  'use strict';
58299
58651
 
58300
58652
  const opts = require('./propertyOptions');
@@ -58459,7 +58811,7 @@ Object.defineProperty(VirtualOptions.prototype, 'limit', opts);
58459
58811
  Object.defineProperty(VirtualOptions.prototype, 'perDocumentLimit', opts);
58460
58812
 
58461
58813
  module.exports = VirtualOptions;
58462
- },{"./propertyOptions":269}],269:[function(require,module,exports){
58814
+ },{"./propertyOptions":271}],271:[function(require,module,exports){
58463
58815
  'use strict';
58464
58816
 
58465
58817
  module.exports = Object.freeze({
@@ -58468,7 +58820,7 @@ module.exports = Object.freeze({
58468
58820
  writable: true,
58469
58821
  value: void 0
58470
58822
  });
58471
- },{}],270:[function(require,module,exports){
58823
+ },{}],272:[function(require,module,exports){
58472
58824
  'use strict';
58473
58825
 
58474
58826
  /*!
@@ -58498,7 +58850,7 @@ function idGetter() {
58498
58850
  return null;
58499
58851
  }
58500
58852
 
58501
- },{}],271:[function(require,module,exports){
58853
+ },{}],273:[function(require,module,exports){
58502
58854
  (function (global){(function (){
58503
58855
  /*!
58504
58856
  * ignore
@@ -58551,7 +58903,7 @@ store.set(global.Promise);
58551
58903
  module.exports = store;
58552
58904
 
58553
58905
  }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
58554
- },{"assert":102,"mquery":316}],272:[function(require,module,exports){
58906
+ },{"assert":102,"mquery":318}],274:[function(require,module,exports){
58555
58907
  'use strict';
58556
58908
 
58557
58909
  /*!
@@ -58585,6 +58937,10 @@ exports.preparePopulationOptions = function preparePopulationOptions(query, opti
58585
58937
  forEach(makeLean(options.lean));
58586
58938
  }
58587
58939
 
58940
+ pop.forEach(opts => {
58941
+ opts._localModel = query.model;
58942
+ });
58943
+
58588
58944
  return pop;
58589
58945
  };
58590
58946
 
@@ -58625,6 +58981,9 @@ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query,
58625
58981
  pop.forEach(p => {
58626
58982
  p._queryProjection = projection;
58627
58983
  });
58984
+ pop.forEach(opts => {
58985
+ opts._localModel = query.model;
58986
+ });
58628
58987
 
58629
58988
  return pop;
58630
58989
  };
@@ -58639,7 +58998,7 @@ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query,
58639
58998
  *
58640
58999
  * @return {Document}
58641
59000
  */
58642
- exports.createModel = function createModel(model, doc, fields, userProvidedFields) {
59001
+ exports.createModel = function createModel(model, doc, fields, userProvidedFields, options) {
58643
59002
  model.hooks.execPreSync('createModel', doc);
58644
59003
  const discriminatorMapping = model.schema ?
58645
59004
  model.schema.discriminatorMapping :
@@ -58651,18 +59010,22 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
58651
59010
 
58652
59011
  const value = doc[key];
58653
59012
  if (key && value && model.discriminators) {
58654
- const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value);
59013
+ const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value);
58655
59014
  if (discriminator) {
58656
59015
  const _fields = clone(userProvidedFields);
58657
59016
  exports.applyPaths(_fields, discriminator.schema);
58658
59017
  return new discriminator(undefined, _fields, true);
58659
59018
  }
58660
59019
  }
58661
-
59020
+ if (typeof options === 'undefined') {
59021
+ options = {};
59022
+ options.defaults = true;
59023
+ }
58662
59024
  return new model(undefined, fields, {
58663
59025
  skipId: true,
58664
59026
  isNew: false,
58665
- willInit: true
59027
+ willInit: true,
59028
+ defaults: options.defaults
58666
59029
  });
58667
59030
  };
58668
59031
 
@@ -58753,7 +59116,11 @@ exports.applyPaths = function applyPaths(fields, schema) {
58753
59116
  schema.eachPath(function(path, type) {
58754
59117
  if (prefix) path = prefix + '.' + path;
58755
59118
 
58756
- const addedPath = analyzePath(path, type);
59119
+ let addedPath = analyzePath(path, type);
59120
+ // arrays
59121
+ if (addedPath == null && type.$isMongooseArray && !type.$isMongooseDocumentArray) {
59122
+ addedPath = analyzePath(path, type.caster);
59123
+ }
58757
59124
  if (addedPath != null) {
58758
59125
  addedPaths.push(addedPath);
58759
59126
  }
@@ -58868,7 +59235,7 @@ exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback)
58868
59235
  };
58869
59236
  };
58870
59237
 
58871
- },{"./helpers/clone":218,"./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection":220,"./helpers/discriminator/getDiscriminatorByValue":222,"./helpers/get":228,"./helpers/projection/isDefiningProjection":238}],273:[function(require,module,exports){
59238
+ },{"./helpers/clone":218,"./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection":221,"./helpers/discriminator/getDiscriminatorByValue":223,"./helpers/get":229,"./helpers/projection/isDefiningProjection":240}],275:[function(require,module,exports){
58872
59239
  (function (Buffer){(function (){
58873
59240
  'use strict';
58874
59241
 
@@ -58886,6 +59253,7 @@ const VirtualType = require('./virtualtype');
58886
59253
  const addAutoId = require('./helpers/schema/addAutoId');
58887
59254
  const arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol;
58888
59255
  const get = require('./helpers/get');
59256
+ const getConstructorName = require('./helpers/getConstructorName');
58889
59257
  const getIndexes = require('./helpers/schema/getIndexes');
58890
59258
  const merge = require('./helpers/schema/merge');
58891
59259
  const mpath = require('mpath');
@@ -58925,6 +59293,7 @@ let id = 0;
58925
59293
  * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
58926
59294
  * - [capped](/docs/guide.html#capped): bool - defaults to false
58927
59295
  * - [collection](/docs/guide.html#collection): string - no default
59296
+ * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t`
58928
59297
  * - [id](/docs/guide.html#id): bool - defaults to true
58929
59298
  * - [_id](/docs/guide.html#_id): bool - defaults to true
58930
59299
  * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
@@ -58985,6 +59354,7 @@ function Schema(obj, options) {
58985
59354
  this.plugins = [];
58986
59355
  // For internal debugging. Do not use this to try to save a schema in MDB.
58987
59356
  this.$id = ++id;
59357
+ this.mapPaths = [];
58988
59358
 
58989
59359
  this.s = {
58990
59360
  hooks: new Kareem()
@@ -59191,6 +59561,7 @@ Schema.prototype.clone = function() {
59191
59561
  s.$globalPluginsApplied = this.$globalPluginsApplied;
59192
59562
  s.$isRootDiscriminator = this.$isRootDiscriminator;
59193
59563
  s.$implicitlyCreated = this.$implicitlyCreated;
59564
+ s.mapPaths = [].concat(this.mapPaths);
59194
59565
 
59195
59566
  if (this.discriminatorMapping != null) {
59196
59567
  s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
@@ -59338,6 +59709,11 @@ Schema.prototype.add = function add(obj, prefix) {
59338
59709
  }
59339
59710
 
59340
59711
  prefix = prefix || '';
59712
+ // avoid prototype pollution
59713
+ if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
59714
+ return this;
59715
+ }
59716
+
59341
59717
  const keys = Object.keys(obj);
59342
59718
 
59343
59719
  for (const key of keys) {
@@ -59463,7 +59839,6 @@ reserved.isNew =
59463
59839
  reserved.populated =
59464
59840
  reserved.remove =
59465
59841
  reserved.save =
59466
- reserved.schema =
59467
59842
  reserved.toObject =
59468
59843
  reserved.validate = 1;
59469
59844
 
@@ -59560,8 +59935,13 @@ Schema.prototype.path = function(path, obj) {
59560
59935
  !utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
59561
59936
  _mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
59562
59937
  }
59938
+ if (utils.hasUserDefinedProperty(obj, 'ref')) {
59939
+ _mapType = { type: _mapType, ref: obj.ref };
59940
+ }
59941
+
59563
59942
  this.paths[mapPath] = this.interpretAsType(mapPath,
59564
59943
  _mapType, this.options);
59944
+ this.mapPaths.push(this.paths[mapPath]);
59565
59945
  schemaType.$__schemaType = this.paths[mapPath];
59566
59946
  }
59567
59947
 
@@ -59638,19 +60018,25 @@ Schema.prototype.path = function(path, obj) {
59638
60018
 
59639
60019
  if (schemaType.$isMongooseDocumentArray) {
59640
60020
  for (const key of Object.keys(schemaType.schema.paths)) {
59641
- this.subpaths[path + '.' + key] = schemaType.schema.paths[key];
59642
- schemaType.schema.paths[key].$isUnderneathDocArray = true;
60021
+ const _schemaType = schemaType.schema.paths[key];
60022
+ this.subpaths[path + '.' + key] = _schemaType;
60023
+ if (typeof _schemaType === 'object' && _schemaType != null) {
60024
+ _schemaType.$isUnderneathDocArray = true;
60025
+ }
59643
60026
  }
59644
60027
  for (const key of Object.keys(schemaType.schema.subpaths)) {
59645
- this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key];
59646
- schemaType.schema.subpaths[key].$isUnderneathDocArray = true;
60028
+ const _schemaType = schemaType.schema.subpaths[key];
60029
+ this.subpaths[path + '.' + key] = _schemaType;
60030
+ if (typeof _schemaType === 'object' && _schemaType != null) {
60031
+ _schemaType.$isUnderneathDocArray = true;
60032
+ }
59647
60033
  }
59648
60034
  for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
59649
- if (typeof schemaType.schema.singleNestedPaths[cleanPath] !== 'object') {
59650
- continue;
60035
+ const _schemaType = schemaType.schema.singleNestedPaths[key];
60036
+ this.subpaths[path + '.' + key] = _schemaType;
60037
+ if (typeof _schemaType === 'object' && _schemaType != null) {
60038
+ _schemaType.$isUnderneathDocArray = true;
59651
60039
  }
59652
- this.subpaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key];
59653
- schemaType.schema.singleNestedPaths[key].$isUnderneathDocArray = true;
59654
60040
  }
59655
60041
  }
59656
60042
 
@@ -59708,10 +60094,11 @@ function _pathToPositionalSyntax(path) {
59708
60094
  */
59709
60095
 
59710
60096
  function getMapPath(schema, path) {
59711
- for (const _path of Object.keys(schema.paths)) {
59712
- if (!_path.includes('.$*')) {
59713
- continue;
59714
- }
60097
+ if (schema.mapPaths.length === 0) {
60098
+ return null;
60099
+ }
60100
+ for (const val of schema.mapPaths) {
60101
+ const _path = val.path;
59715
60102
  const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
59716
60103
  if (re.test(path)) {
59717
60104
  return schema.paths[_path];
@@ -59785,11 +60172,21 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
59785
60172
  : type[0];
59786
60173
 
59787
60174
  if (cast && cast.instanceOfSchema) {
60175
+ if (!(cast instanceof Schema)) {
60176
+ throw new TypeError('Schema for array path `' + path +
60177
+ '` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' +
60178
+ 'of Mongoose everywhere with `npm list mongoose`.');
60179
+ }
59788
60180
  return new MongooseTypes.DocumentArray(path, cast, obj);
59789
60181
  }
59790
60182
  if (cast &&
59791
60183
  cast[options.typeKey] &&
59792
60184
  cast[options.typeKey].instanceOfSchema) {
60185
+ if (!(cast[options.typeKey] instanceof Schema)) {
60186
+ throw new TypeError('Schema for array path `' + path +
60187
+ '` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' +
60188
+ 'of Mongoose everywhere with `npm list mongoose`.');
60189
+ }
59793
60190
  return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
59794
60191
  }
59795
60192
 
@@ -59842,6 +60239,11 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
59842
60239
  ? type
59843
60240
  : type.schemaName || utils.getFunctionName(type);
59844
60241
 
60242
+ // For Jest 26+, see #10296
60243
+ if (name === 'ClockDate') {
60244
+ name = 'Date';
60245
+ }
60246
+
59845
60247
  if (!MongooseTypes.hasOwnProperty(name)) {
59846
60248
  throw new TypeError('Invalid schema configuration: ' +
59847
60249
  `\`${name}\` is not a valid type within the array \`${path}\`.` +
@@ -59872,6 +60274,10 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
59872
60274
  if (name === 'ObjectID') {
59873
60275
  name = 'ObjectId';
59874
60276
  }
60277
+ // For Jest 26+, see #10296
60278
+ if (name === 'ClockDate') {
60279
+ name = 'Date';
60280
+ }
59875
60281
 
59876
60282
  if (MongooseTypes[name] == null) {
59877
60283
  throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
@@ -60326,7 +60732,7 @@ Schema.prototype.plugin = function(fn, opts) {
60326
60732
  * fizz.purr();
60327
60733
  * fizz.scratch();
60328
60734
  *
60329
- * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](./guide.html#methods)
60735
+ * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods)
60330
60736
  *
60331
60737
  * @param {String|Object} method name
60332
60738
  * @param {Function} [fn]
@@ -60388,7 +60794,7 @@ Schema.prototype.static = function(name, fn) {
60388
60794
  *
60389
60795
  * @param {Object} fields
60390
60796
  * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
60391
- * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
60797
+ * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
60392
60798
  * @api public
60393
60799
  */
60394
60800
 
@@ -60509,8 +60915,8 @@ Object.defineProperty(Schema, 'indexTypes', {
60509
60915
  });
60510
60916
 
60511
60917
  /**
60512
- * Returns a list of indexes that this schema declares, via `schema.index()`
60513
- * or by `index: true` in a path's options.
60918
+ * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
60919
+ * Indexes are expressed as an array `[spec, options]`.
60514
60920
  *
60515
60921
  * ####Example:
60516
60922
  *
@@ -60523,6 +60929,17 @@ Object.defineProperty(Schema, 'indexTypes', {
60523
60929
  * // [ { registeredAt: 1 }, { background: true } ] ]
60524
60930
  * userSchema.indexes();
60525
60931
  *
60932
+ * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
60933
+ * For example, the below plugin makes every index unique by default.
60934
+ *
60935
+ * function myPlugin(schema) {
60936
+ * for (const index of schema.indexes()) {
60937
+ * if (index[1].unique === undefined) {
60938
+ * index[1].unique = true;
60939
+ * }
60940
+ * }
60941
+ * }
60942
+ *
60526
60943
  * @api public
60527
60944
  * @return {Array} list of indexes defined in the schema
60528
60945
  */
@@ -60546,7 +60963,7 @@ Schema.prototype.indexes = function() {
60546
60963
  */
60547
60964
 
60548
60965
  Schema.prototype.virtual = function(name, options) {
60549
- if (name instanceof VirtualType || (name != null && name.constructor.name === 'VirtualType')) {
60966
+ if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
60550
60967
  return this.virtual(name.path, name.options);
60551
60968
  }
60552
60969
 
@@ -60730,9 +61147,9 @@ function _deletePath(schema, name) {
60730
61147
  /**
60731
61148
  * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
60732
61149
  * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
60733
- * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
60734
- * [statics](http://mongoosejs.com/docs/guide.html#statics), and
60735
- * [methods](http://mongoosejs.com/docs/guide.html#methods).
61150
+ * to schema [virtuals](/docs/guide.html#virtuals),
61151
+ * [statics](/docs/guide.html#statics), and
61152
+ * [methods](/docs/guide.html#methods).
60736
61153
  *
60737
61154
  * ####Example:
60738
61155
  *
@@ -60777,12 +61194,12 @@ Schema.prototype.loadClass = function(model, virtualsOnly) {
60777
61194
  // Add static methods
60778
61195
  if (!virtualsOnly) {
60779
61196
  Object.getOwnPropertyNames(model).forEach(function(name) {
60780
- if (name.match(/^(length|name|prototype)$/)) {
61197
+ if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) {
60781
61198
  return;
60782
61199
  }
60783
- const method = Object.getOwnPropertyDescriptor(model, name);
60784
- if (typeof method.value === 'function') {
60785
- this.static(name, method.value);
61200
+ const prop = Object.getOwnPropertyDescriptor(model, name);
61201
+ if (prop.hasOwnProperty('value')) {
61202
+ this.static(name, prop.value);
60786
61203
  }
60787
61204
  }, this);
60788
61205
  }
@@ -60880,7 +61297,7 @@ Schema.prototype._getSchema = function(path) {
60880
61297
  }
60881
61298
  } else if (foundschema.$isSchemaMap) {
60882
61299
  if (p + 1 >= parts.length) {
60883
- return foundschema.$__schemaType;
61300
+ return foundschema;
60884
61301
  }
60885
61302
  const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema);
60886
61303
  return ret;
@@ -60991,14 +61408,14 @@ module.exports = exports = Schema;
60991
61408
  *
60992
61409
  * ####Types:
60993
61410
  *
60994
- * - [String](#schema-string-js)
60995
- * - [Number](#schema-number-js)
60996
- * - [Boolean](#schema-boolean-js) | Bool
60997
- * - [Array](#schema-array-js)
60998
- * - [Buffer](#schema-buffer-js)
60999
- * - [Date](#schema-date-js)
61000
- * - [ObjectId](#schema-objectid-js) | Oid
61001
- * - [Mixed](#schema-mixed-js)
61411
+ * - [String](/docs/schematypes.html#strings)
61412
+ * - [Number](/docs/schematypes.html#numbers)
61413
+ * - [Boolean](/docs/schematypes.html#booleans) | Bool
61414
+ * - [Array](/docs/schematypes.html#arrays)
61415
+ * - [Buffer](/docs/schematypes.html#buffers)
61416
+ * - [Date](/docs/schematypes.html#dates)
61417
+ * - [ObjectId](/docs/schematypes.html#objectids) | Oid
61418
+ * - [Mixed](/docs/schematypes.html#mixed)
61002
61419
  *
61003
61420
  * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
61004
61421
  *
@@ -61017,7 +61434,7 @@ Schema.Types = MongooseTypes = require('./schema/index');
61017
61434
  exports.ObjectId = MongooseTypes.ObjectId;
61018
61435
 
61019
61436
  }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
61020
- },{"../../is-buffer/index.js":178,"./driver":195,"./error/mongooseError":206,"./helpers/get":228,"./helpers/model/applyHooks":235,"./helpers/populate/validateRef":237,"./helpers/query/applyQueryMiddleware":241,"./helpers/schema/addAutoId":243,"./helpers/schema/getIndexes":245,"./helpers/schema/merge":248,"./helpers/symbols":251,"./helpers/timestamps/setupTimestamps":252,"./options/SchemaTypeOptions":267,"./options/VirtualOptions":268,"./schema/index":281,"./schematype":294,"./utils":306,"./virtualtype":307,"events":176,"kareem":181,"mpath":309,"util":331}],274:[function(require,module,exports){
61437
+ },{"../../is-buffer/index.js":178,"./driver":195,"./error/mongooseError":206,"./helpers/get":229,"./helpers/getConstructorName":230,"./helpers/model/applyHooks":237,"./helpers/populate/validateRef":239,"./helpers/query/applyQueryMiddleware":243,"./helpers/schema/addAutoId":245,"./helpers/schema/getIndexes":247,"./helpers/schema/merge":250,"./helpers/symbols":253,"./helpers/timestamps/setupTimestamps":254,"./options/SchemaTypeOptions":269,"./options/VirtualOptions":270,"./schema/index":283,"./schematype":296,"./utils":308,"./virtualtype":309,"events":176,"kareem":181,"mpath":311,"util":333}],276:[function(require,module,exports){
61021
61438
  'use strict';
61022
61439
 
61023
61440
  /*!
@@ -61355,7 +61772,7 @@ SingleNestedPath.prototype.clone = function() {
61355
61772
  return schematype;
61356
61773
  };
61357
61774
 
61358
- },{"../error/cast":201,"../error/objectExpected":208,"../helpers/discriminator/getConstructor":221,"../helpers/get":228,"../helpers/model/discriminator":236,"../helpers/schema/handleIdOption":246,"../options":256,"../options/SchemaSingleNestedOptions":265,"../schematype":294,"../types/subdocument":305,"./operators/exists":287,"./operators/geospatial":288,"./operators/helpers":289,"events":176}],275:[function(require,module,exports){
61775
+ },{"../error/cast":201,"../error/objectExpected":208,"../helpers/discriminator/getConstructor":222,"../helpers/get":229,"../helpers/model/discriminator":238,"../helpers/schema/handleIdOption":248,"../options":258,"../options/SchemaSingleNestedOptions":267,"../schematype":296,"../types/subdocument":307,"./operators/exists":289,"./operators/geospatial":290,"./operators/helpers":291,"events":176}],277:[function(require,module,exports){
61359
61776
  'use strict';
61360
61777
 
61361
61778
  /*!
@@ -61383,6 +61800,7 @@ let MongooseArray;
61383
61800
  let EmbeddedDoc;
61384
61801
 
61385
61802
  const isNestedArraySymbol = Symbol('mongoose#isNestedArray');
61803
+ const emptyOpts = Object.freeze({});
61386
61804
 
61387
61805
  /**
61388
61806
  * Array SchemaType constructor
@@ -61418,6 +61836,10 @@ function SchemaArray(key, cast, options, schemaOptions) {
61418
61836
  }
61419
61837
  }
61420
61838
 
61839
+ if (options != null && options.ref != null && castOptions.ref == null) {
61840
+ castOptions.ref = options.ref;
61841
+ }
61842
+
61421
61843
  if (cast === Object) {
61422
61844
  cast = Mixed;
61423
61845
  }
@@ -61439,16 +61861,16 @@ function SchemaArray(key, cast, options, schemaOptions) {
61439
61861
  if (typeof caster === 'function' &&
61440
61862
  !caster.$isArraySubdocument &&
61441
61863
  !caster.$isSchemaMap) {
61442
- this.caster = new caster(null, castOptions);
61864
+ const path = this.caster instanceof EmbeddedDoc ? null : key;
61865
+ this.caster = new caster(path, castOptions);
61443
61866
  } else {
61444
61867
  this.caster = caster;
61868
+ if (!(this.caster instanceof EmbeddedDoc)) {
61869
+ this.caster.path = key;
61870
+ }
61445
61871
  }
61446
61872
 
61447
61873
  this.$embeddedSchemaType = this.caster;
61448
-
61449
- if (!(this.caster instanceof EmbeddedDoc)) {
61450
- this.caster.path = key;
61451
- }
61452
61874
  }
61453
61875
 
61454
61876
  this.$isMongooseArray = true;
@@ -61499,6 +61921,10 @@ SchemaArray.schemaName = 'Array';
61499
61921
 
61500
61922
  SchemaArray.options = { castNonArrays: true };
61501
61923
 
61924
+ /*!
61925
+ * ignore
61926
+ */
61927
+
61502
61928
  SchemaArray.defaultOptions = {};
61503
61929
 
61504
61930
  /**
@@ -61516,7 +61942,6 @@ SchemaArray.defaultOptions = {};
61516
61942
  * @param {*} value - value for option
61517
61943
  * @return {undefined}
61518
61944
  * @function set
61519
- * @static
61520
61945
  * @api public
61521
61946
  */
61522
61947
  SchemaArray.set = SchemaType.set;
@@ -61549,7 +61974,6 @@ SchemaArray._checkRequired = SchemaType.prototype.checkRequired;
61549
61974
  * @param {Function} fn
61550
61975
  * @return {Function}
61551
61976
  * @function checkRequired
61552
- * @static
61553
61977
  * @api public
61554
61978
  */
61555
61979
 
@@ -61619,7 +62043,7 @@ SchemaArray.prototype.enum = function() {
61619
62043
  */
61620
62044
 
61621
62045
  SchemaArray.prototype.applyGetters = function(value, scope) {
61622
- if (scope != null && scope.populated(this.path)) {
62046
+ if (scope != null && scope.$__ != null && scope.populated(this.path)) {
61623
62047
  // means the object id was populated
61624
62048
  return value;
61625
62049
  }
@@ -61635,14 +62059,14 @@ SchemaArray.prototype.applyGetters = function(value, scope) {
61635
62059
  };
61636
62060
 
61637
62061
  SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) {
61638
- if (this.casterConstructor instanceof SchemaArray &&
62062
+ if (this.casterConstructor.$isMongooseArray &&
61639
62063
  SchemaArray.options.castNonArrays &&
61640
62064
  !this[isNestedArraySymbol]) {
61641
62065
  // Check nesting levels and wrap in array if necessary
61642
62066
  let depth = 0;
61643
62067
  let arr = this;
61644
62068
  while (arr != null &&
61645
- arr instanceof SchemaArray &&
62069
+ arr.$isMongooseArray &&
61646
62070
  !arr.$isMongooseDocumentArray) {
61647
62071
  ++depth;
61648
62072
  arr = arr.casterConstructor;
@@ -61679,7 +62103,8 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
61679
62103
  let l;
61680
62104
 
61681
62105
  if (Array.isArray(value)) {
61682
- if (!value.length && doc) {
62106
+ const len = value.length;
62107
+ if (!len && doc) {
61683
62108
  const indexes = doc.schema.indexedPaths();
61684
62109
 
61685
62110
  const arrayPath = this.path;
@@ -61704,39 +62129,35 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
61704
62129
  }
61705
62130
  }
61706
62131
 
61707
- if (!(value && value.isMongooseArray)) {
61708
- value = MongooseArray(value, get(options, 'path', null) || this._arrayPath || this.path, doc, this);
61709
- } else if (value && value.isMongooseArray) {
61710
- // We need to create a new array, otherwise change tracking will
61711
- // update the old doc (gh-4449)
61712
- value = MongooseArray(value, get(options, 'path', null) || this._arrayPath || this.path, doc, this);
61713
- }
62132
+ options = options || emptyOpts;
62133
+
62134
+ value = MongooseArray(value, options.path || this._arrayPath || this.path, doc, this);
61714
62135
 
61715
- const isPopulated = doc != null && doc.$__ != null && doc.populated(this.path);
61716
- if (isPopulated && init) {
62136
+ if (init && doc != null && doc.$__ != null && doc.populated(this.path)) {
61717
62137
  return value;
61718
62138
  }
61719
62139
 
61720
62140
  const caster = this.caster;
62141
+ const isMongooseArray = caster.$isMongooseArray;
62142
+ const isArrayOfNumbers = caster.instance === 'Number';
61721
62143
  if (caster && this.casterConstructor !== Mixed) {
61722
62144
  try {
61723
- const len = value.length;
61724
62145
  for (i = 0; i < len; i++) {
61725
62146
  // Special case: number arrays disallow undefined.
61726
62147
  // Re: gh-840
61727
62148
  // See commit 1298fe92d2c790a90594bd08199e45a4a09162a6
61728
- if (caster.instance === 'Number' && value[i] === void 0) {
62149
+ if (isArrayOfNumbers && value[i] === void 0) {
61729
62150
  throw new MongooseError('Mongoose number arrays disallow storing undefined');
61730
62151
  }
61731
62152
  const opts = {};
61732
62153
  // Perf: creating `arrayPath` is expensive for large arrays.
61733
62154
  // We only need `arrayPath` if this is a nested array, so
61734
62155
  // skip if possible.
61735
- if (caster.$isMongooseArray) {
61736
- if (options != null && options.arrayPath != null) {
61737
- opts.arrayPath = options.arrayPath + '.' + i;
61738
- } else if (this.caster._arrayParentPath != null) {
61739
- opts.arrayPath = this.caster._arrayParentPath + '.' + i;
62156
+ if (isMongooseArray) {
62157
+ if (options.arrayPath != null) {
62158
+ opts.arrayPathIndex = i;
62159
+ } else if (caster._arrayParentPath != null) {
62160
+ opts.arrayPathIndex = i;
61740
62161
  }
61741
62162
  }
61742
62163
  value[i] = caster.applySetters(value[i], doc, init, void 0, opts);
@@ -61762,12 +62183,50 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
61762
62183
  throw new CastError('Array', util.inspect(value), this.path, null, this);
61763
62184
  };
61764
62185
 
62186
+ /*!
62187
+ * ignore
62188
+ */
62189
+
62190
+ SchemaArray.prototype._castForPopulate = function _castForPopulate(value, doc) {
62191
+ // lazy load
62192
+ MongooseArray || (MongooseArray = require('../types').Array);
62193
+
62194
+ if (Array.isArray(value)) {
62195
+ let i;
62196
+ const len = value.length;
62197
+
62198
+ const caster = this.caster;
62199
+ if (caster && this.casterConstructor !== Mixed) {
62200
+ try {
62201
+ for (i = 0; i < len; i++) {
62202
+ const opts = {};
62203
+ // Perf: creating `arrayPath` is expensive for large arrays.
62204
+ // We only need `arrayPath` if this is a nested array, so
62205
+ // skip if possible.
62206
+ if (caster.$isMongooseArray && caster._arrayParentPath != null) {
62207
+ opts.arrayPathIndex = i;
62208
+ }
62209
+
62210
+ value[i] = caster.cast(value[i], doc, false, void 0, opts);
62211
+ }
62212
+ } catch (e) {
62213
+ // rethrow
62214
+ throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this);
62215
+ }
62216
+ }
62217
+
62218
+ return value;
62219
+ }
62220
+
62221
+ throw new CastError('Array', util.inspect(value), this.path, null, this);
62222
+ };
62223
+
61765
62224
  /*!
61766
62225
  * Ignore
61767
62226
  */
61768
62227
 
61769
62228
  SchemaArray.prototype.discriminator = function(name, schema) {
61770
- let arr = this; // eslint-disable-line consistent-this
62229
+ let arr = this;
61771
62230
  while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) {
61772
62231
  arr = arr.casterConstructor;
61773
62232
  if (arr == null || typeof arr === 'function') {
@@ -61825,7 +62284,7 @@ SchemaArray.prototype.castForQuery = function($conditional, value) {
61825
62284
  Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
61826
62285
  Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
61827
62286
  } else {
61828
- const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]);
62287
+ const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]);
61829
62288
  if (constructorByValue) {
61830
62289
  Constructor = constructorByValue;
61831
62290
  }
@@ -61966,7 +62425,7 @@ handle.$in = SchemaType.prototype.$conditionalHandlers.$in;
61966
62425
 
61967
62426
  module.exports = SchemaArray;
61968
62427
 
61969
- },{"../cast":186,"../error/mongooseError":206,"../helpers/arrayDepth":217,"../helpers/discriminator/getDiscriminatorByValue":222,"../helpers/get":228,"../helpers/query/isOperator":242,"../options/SchemaArrayOptions":258,"../schematype":294,"../types":302,"../utils":306,"./index.js":281,"./mixed":283,"./operators/exists":287,"./operators/geospatial":288,"./operators/helpers":289,"./operators/type":291,"util":331}],276:[function(require,module,exports){
62428
+ },{"../cast":186,"../error/mongooseError":206,"../helpers/arrayDepth":217,"../helpers/discriminator/getDiscriminatorByValue":223,"../helpers/get":229,"../helpers/query/isOperator":244,"../options/SchemaArrayOptions":260,"../schematype":296,"../types":304,"../utils":308,"./index.js":283,"./mixed":285,"./operators/exists":289,"./operators/geospatial":290,"./operators/helpers":291,"./operators/type":293,"util":333}],278:[function(require,module,exports){
61970
62429
  'use strict';
61971
62430
 
61972
62431
  /*!
@@ -62238,7 +62697,7 @@ SchemaBoolean.prototype._castNullish = function _castNullish(v) {
62238
62697
 
62239
62698
  module.exports = SchemaBoolean;
62240
62699
 
62241
- },{"../cast/boolean":187,"../error/cast":201,"../schematype":294,"../utils":306}],277:[function(require,module,exports){
62700
+ },{"../cast/boolean":187,"../error/cast":201,"../schematype":296,"../utils":308}],279:[function(require,module,exports){
62242
62701
  (function (Buffer){(function (){
62243
62702
  /*!
62244
62703
  * Module dependencies.
@@ -62252,11 +62711,8 @@ const SchemaType = require('../schematype');
62252
62711
  const handleBitwiseOperator = require('./operators/bitwise');
62253
62712
  const utils = require('../utils');
62254
62713
 
62255
- const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
62256
-
62257
62714
  const Binary = MongooseBuffer.Binary;
62258
62715
  const CastError = SchemaType.CastError;
62259
- let Document;
62260
62716
 
62261
62717
  /**
62262
62718
  * Buffer SchemaType constructor
@@ -62366,36 +62822,30 @@ SchemaBuffer.prototype.checkRequired = function(value, doc) {
62366
62822
  SchemaBuffer.prototype.cast = function(value, doc, init) {
62367
62823
  let ret;
62368
62824
  if (SchemaType._isRef(this, value, doc, init)) {
62369
- // wait! we may need to cast this to a document
62370
-
62371
- if (value === null || value === undefined) {
62825
+ if (value && value.isMongooseBuffer) {
62372
62826
  return value;
62373
62827
  }
62374
62828
 
62375
- // lazy load
62376
- Document || (Document = require('./../document'));
62377
-
62378
- if (value instanceof Document) {
62379
- value.$__.wasPopulated = true;
62829
+ if (Buffer.isBuffer(value)) {
62830
+ if (!value || !value.isMongooseBuffer) {
62831
+ value = new MongooseBuffer(value, [this.path, doc]);
62832
+ if (this.options.subtype != null) {
62833
+ value._subtype = this.options.subtype;
62834
+ }
62835
+ }
62380
62836
  return value;
62381
62837
  }
62382
62838
 
62383
- // setting a populated path
62384
- if (Buffer.isBuffer(value)) {
62385
- return value;
62386
- } else if (!utils.isObject(value)) {
62387
- throw new CastError('Buffer', value, this.path, null, this);
62839
+ if (value instanceof Binary) {
62840
+ ret = new MongooseBuffer(value.value(true), [this.path, doc]);
62841
+ if (typeof value.sub_type !== 'number') {
62842
+ throw new CastError('Buffer', value, this.path, null, this);
62843
+ }
62844
+ ret._subtype = value.sub_type;
62845
+ return ret;
62388
62846
  }
62389
62847
 
62390
- // Handle the case where user directly sets a populated
62391
- // path to a plain object; cast to the Model used in
62392
- // the population query.
62393
- const path = doc.$__fullPath(this.path);
62394
- const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
62395
- const pop = owner.populated(path, true);
62396
- ret = new pop.options[populateModelSymbol](value);
62397
- ret.$__.wasPopulated = true;
62398
- return ret;
62848
+ return this._castRef(value, doc, init);
62399
62849
  }
62400
62850
 
62401
62851
  // documents
@@ -62518,7 +62968,7 @@ SchemaBuffer.prototype.castForQuery = function($conditional, val) {
62518
62968
  module.exports = SchemaBuffer;
62519
62969
 
62520
62970
  }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
62521
- },{"../../../is-buffer/index.js":178,"../helpers/symbols":251,"../options/SchemaBufferOptions":259,"../schematype":294,"../types/buffer":297,"../utils":306,"./../document":193,"./operators/bitwise":286}],278:[function(require,module,exports){
62971
+ },{"../../../is-buffer/index.js":178,"../options/SchemaBufferOptions":261,"../schematype":296,"../types/buffer":299,"../utils":308,"./operators/bitwise":288}],280:[function(require,module,exports){
62522
62972
  /*!
62523
62973
  * Module requirements.
62524
62974
  */
@@ -62529,6 +62979,7 @@ const MongooseError = require('../error/index');
62529
62979
  const SchemaDateOptions = require('../options/SchemaDateOptions');
62530
62980
  const SchemaType = require('../schematype');
62531
62981
  const castDate = require('../cast/date');
62982
+ const getConstructorName = require('../helpers/getConstructorName');
62532
62983
  const utils = require('../utils');
62533
62984
 
62534
62985
  const CastError = SchemaType.CastError;
@@ -62668,7 +63119,7 @@ SchemaDate._defaultCaster = v => {
62668
63119
  */
62669
63120
 
62670
63121
  SchemaDate.prototype.expires = function(when) {
62671
- if (!this._index || this._index.constructor.name !== 'Object') {
63122
+ if (getConstructorName(this._index) !== 'Object') {
62672
63123
  this._index = {};
62673
63124
  }
62674
63125
 
@@ -62922,8 +63373,7 @@ SchemaDate.prototype.castForQuery = function($conditional, val) {
62922
63373
 
62923
63374
  module.exports = SchemaDate;
62924
63375
 
62925
- },{"../cast/date":188,"../error/index":203,"../options/SchemaDateOptions":260,"../schematype":294,"../utils":306}],279:[function(require,module,exports){
62926
- (function (Buffer){(function (){
63376
+ },{"../cast/date":188,"../error/index":203,"../helpers/getConstructorName":230,"../options/SchemaDateOptions":262,"../schematype":296,"../utils":308}],281:[function(require,module,exports){
62927
63377
  /*!
62928
63378
  * Module dependencies.
62929
63379
  */
@@ -62936,10 +63386,6 @@ const Decimal128Type = require('../types/decimal128');
62936
63386
  const castDecimal128 = require('../cast/decimal128');
62937
63387
  const utils = require('../utils');
62938
63388
 
62939
- const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
62940
-
62941
- let Document;
62942
-
62943
63389
  /**
62944
63390
  * Decimal128 SchemaType constructor.
62945
63391
  *
@@ -63094,44 +63540,11 @@ Decimal128.prototype.checkRequired = function checkRequired(value, doc) {
63094
63540
 
63095
63541
  Decimal128.prototype.cast = function(value, doc, init) {
63096
63542
  if (SchemaType._isRef(this, value, doc, init)) {
63097
- // wait! we may need to cast this to a document
63098
-
63099
- if (value === null || value === undefined) {
63100
- return value;
63101
- }
63102
-
63103
- // lazy load
63104
- Document || (Document = require('./../document'));
63105
-
63106
- if (value instanceof Document) {
63107
- value.$__.wasPopulated = true;
63108
- return value;
63109
- }
63110
-
63111
- // setting a populated path
63112
63543
  if (value instanceof Decimal128Type) {
63113
63544
  return value;
63114
- } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
63115
- throw new CastError('Decimal128', value, this.path, null, this);
63116
- }
63117
-
63118
- // Handle the case where user directly sets a populated
63119
- // path to a plain object; cast to the Model used in
63120
- // the population query.
63121
- const path = doc.$__fullPath(this.path);
63122
- const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
63123
- const pop = owner.populated(path, true);
63124
- let ret = value;
63125
- if (!doc.$__.populated ||
63126
- !doc.$__.populated[path] ||
63127
- !doc.$__.populated[path].options ||
63128
- !doc.$__.populated[path].options.options ||
63129
- !doc.$__.populated[path].options.options.lean) {
63130
- ret = new pop.options[populateModelSymbol](value);
63131
- ret.$__.wasPopulated = true;
63132
63545
  }
63133
63546
 
63134
- return ret;
63547
+ return this._castRef(value, doc, init);
63135
63548
  }
63136
63549
 
63137
63550
  let castDecimal128;
@@ -63172,8 +63585,7 @@ Decimal128.prototype.$conditionalHandlers =
63172
63585
 
63173
63586
  module.exports = Decimal128;
63174
63587
 
63175
- }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
63176
- },{"../../../is-buffer/index.js":178,"../cast/decimal128":189,"../helpers/symbols":251,"../schematype":294,"../types/decimal128":299,"../utils":306,"./../document":193}],280:[function(require,module,exports){
63588
+ },{"../cast/decimal128":189,"../schematype":296,"../types/decimal128":301,"../utils":308}],282:[function(require,module,exports){
63177
63589
  'use strict';
63178
63590
 
63179
63591
  /*!
@@ -63194,6 +63606,7 @@ const util = require('util');
63194
63606
  const utils = require('../utils');
63195
63607
  const getConstructor = require('../helpers/discriminator/getConstructor');
63196
63608
 
63609
+ const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
63197
63610
  const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
63198
63611
  const documentArrayParent = require('../helpers/symbols').documentArrayParent;
63199
63612
 
@@ -63577,8 +63990,12 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
63577
63990
  value = new MongooseDocumentArray(value, this.path, doc);
63578
63991
  }
63579
63992
 
63580
- if (options.arrayPath != null) {
63581
- value[arrayPathSymbol] = options.arrayPath;
63993
+ if (prev != null) {
63994
+ value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {};
63995
+ }
63996
+
63997
+ if (options.arrayPathIndex != null) {
63998
+ value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex;
63582
63999
  }
63583
64000
 
63584
64001
  const len = value.length;
@@ -63738,7 +64155,7 @@ DocumentArrayPath.set = SchemaType.set;
63738
64155
 
63739
64156
  module.exports = DocumentArrayPath;
63740
64157
 
63741
- },{"../error/cast":201,"../error/validation":214,"../helpers/discriminator/getConstructor":221,"../helpers/get":228,"../helpers/model/discriminator":236,"../helpers/schema/handleIdOption":246,"../helpers/symbols":251,"../options/SchemaDocumentArrayOptions":261,"../schematype":294,"../types/documentarray":300,"../types/embedded":301,"../utils":306,"./array":275,"events":176,"util":331}],281:[function(require,module,exports){
64158
+ },{"../error/cast":201,"../error/validation":214,"../helpers/discriminator/getConstructor":222,"../helpers/get":229,"../helpers/model/discriminator":238,"../helpers/schema/handleIdOption":248,"../helpers/symbols":253,"../options/SchemaDocumentArrayOptions":263,"../schematype":296,"../types/documentarray":302,"../types/embedded":303,"../utils":308,"./array":277,"events":176,"util":333}],283:[function(require,module,exports){
63742
64159
 
63743
64160
  /*!
63744
64161
  * Module exports.
@@ -63777,7 +64194,7 @@ exports.Object = exports.Mixed;
63777
64194
  exports.Bool = exports.Boolean;
63778
64195
  exports.ObjectID = exports.ObjectId;
63779
64196
 
63780
- },{"./SingleNestedPath":274,"./array":275,"./boolean":276,"./buffer":277,"./date":278,"./decimal128":279,"./documentarray":280,"./map":282,"./mixed":283,"./number":284,"./objectid":285,"./string":292}],282:[function(require,module,exports){
64197
+ },{"./SingleNestedPath":276,"./array":277,"./boolean":278,"./buffer":279,"./date":280,"./decimal128":281,"./documentarray":282,"./map":284,"./mixed":285,"./number":286,"./objectid":287,"./string":294}],284:[function(require,module,exports){
63781
64198
  (function (global){(function (){
63782
64199
  'use strict';
63783
64200
 
@@ -63857,7 +64274,7 @@ Map.defaultOptions = {};
63857
64274
  module.exports = Map;
63858
64275
 
63859
64276
  }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
63860
- },{"../options/SchemaMapOptions":262,"../schematype":294,"../types/map":303}],283:[function(require,module,exports){
64277
+ },{"../options/SchemaMapOptions":264,"../schematype":296,"../types/map":305}],285:[function(require,module,exports){
63861
64278
  /*!
63862
64279
  * Module dependencies.
63863
64280
  */
@@ -63867,6 +64284,7 @@ module.exports = Map;
63867
64284
  const SchemaType = require('../schematype');
63868
64285
  const symbols = require('./symbols');
63869
64286
  const isObject = require('../helpers/isObject');
64287
+ const utils = require('../utils');
63870
64288
 
63871
64289
  /**
63872
64290
  * Mixed SchemaType constructor.
@@ -63963,6 +64381,9 @@ Mixed.set = SchemaType.set;
63963
64381
  */
63964
64382
 
63965
64383
  Mixed.prototype.cast = function(val) {
64384
+ if (val instanceof Error) {
64385
+ return utils.errorToPOJO(val);
64386
+ }
63966
64387
  return val;
63967
64388
  };
63968
64389
 
@@ -63987,8 +64408,7 @@ Mixed.prototype.castForQuery = function($cond, val) {
63987
64408
 
63988
64409
  module.exports = Mixed;
63989
64410
 
63990
- },{"../helpers/isObject":233,"../schematype":294,"./symbols":293}],284:[function(require,module,exports){
63991
- (function (Buffer){(function (){
64411
+ },{"../helpers/isObject":235,"../schematype":296,"../utils":308,"./symbols":295}],286:[function(require,module,exports){
63992
64412
  'use strict';
63993
64413
 
63994
64414
  /*!
@@ -64002,10 +64422,7 @@ const castNumber = require('../cast/number');
64002
64422
  const handleBitwiseOperator = require('./operators/bitwise');
64003
64423
  const utils = require('../utils');
64004
64424
 
64005
- const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
64006
-
64007
64425
  const CastError = SchemaType.CastError;
64008
- let Document;
64009
64426
 
64010
64427
  /**
64011
64428
  * Number SchemaType constructor.
@@ -64341,36 +64758,11 @@ SchemaNumber.prototype.enum = function(values, message) {
64341
64758
 
64342
64759
  SchemaNumber.prototype.cast = function(value, doc, init) {
64343
64760
  if (SchemaType._isRef(this, value, doc, init)) {
64344
- // wait! we may need to cast this to a document
64345
-
64346
- if (value === null || value === undefined) {
64347
- return value;
64348
- }
64349
-
64350
- // lazy load
64351
- Document || (Document = require('./../document'));
64352
-
64353
- if (value instanceof Document) {
64354
- value.$__.wasPopulated = true;
64355
- return value;
64356
- }
64357
-
64358
- // setting a populated path
64359
64761
  if (typeof value === 'number') {
64360
64762
  return value;
64361
- } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
64362
- throw new CastError('Number', value, this.path, null, this);
64363
64763
  }
64364
64764
 
64365
- // Handle the case where user directly sets a populated
64366
- // path to a plain object; cast to the Model used in
64367
- // the population query.
64368
- const path = doc.$__fullPath(this.path);
64369
- const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
64370
- const pop = owner.populated(path, true);
64371
- const ret = new pop.options[populateModelSymbol](value);
64372
- ret.$__.wasPopulated = true;
64373
- return ret;
64765
+ return this._castRef(value, doc, init);
64374
64766
  }
64375
64767
 
64376
64768
  const val = value && typeof value._id !== 'undefined' ?
@@ -64451,9 +64843,7 @@ SchemaNumber.prototype.castForQuery = function($conditional, val) {
64451
64843
 
64452
64844
  module.exports = SchemaNumber;
64453
64845
 
64454
- }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
64455
- },{"../../../is-buffer/index.js":178,"../cast/number":190,"../error/index":203,"../helpers/symbols":251,"../options/SchemaNumberOptions":263,"../schematype":294,"../utils":306,"./../document":193,"./operators/bitwise":286}],285:[function(require,module,exports){
64456
- (function (Buffer){(function (){
64846
+ },{"../cast/number":190,"../error/index":203,"../options/SchemaNumberOptions":265,"../schematype":296,"../utils":308,"./operators/bitwise":288}],287:[function(require,module,exports){
64457
64847
  /*!
64458
64848
  * Module dependencies.
64459
64849
  */
@@ -64463,11 +64853,10 @@ module.exports = SchemaNumber;
64463
64853
  const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions');
64464
64854
  const SchemaType = require('../schematype');
64465
64855
  const castObjectId = require('../cast/objectid');
64856
+ const getConstructorName = require('../helpers/getConstructorName');
64466
64857
  const oid = require('../types/objectid');
64467
64858
  const utils = require('../utils');
64468
64859
 
64469
- const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
64470
-
64471
64860
  const CastError = SchemaType.CastError;
64472
64861
  let Document;
64473
64862
 
@@ -64681,45 +65070,13 @@ ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
64681
65070
  ObjectId.prototype.cast = function(value, doc, init) {
64682
65071
  if (SchemaType._isRef(this, value, doc, init)) {
64683
65072
  // wait! we may need to cast this to a document
64684
-
64685
- if (value === null || value === undefined) {
64686
- return value;
64687
- }
64688
-
64689
- // lazy load
64690
- Document || (Document = require('./../document'));
64691
-
64692
- if (value instanceof Document) {
64693
- value.$__.wasPopulated = true;
64694
- return value;
64695
- }
64696
-
64697
- // setting a populated path
64698
65073
  if (value instanceof oid) {
64699
65074
  return value;
64700
- } else if ((value.constructor.name || '').toLowerCase() === 'objectid') {
65075
+ } else if ((getConstructorName(value) || '').toLowerCase() === 'objectid') {
64701
65076
  return new oid(value.toHexString());
64702
- } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
64703
- throw new CastError('ObjectId', value, this.path, null, this);
64704
- }
64705
-
64706
- // Handle the case where user directly sets a populated
64707
- // path to a plain object; cast to the Model used in
64708
- // the population query.
64709
- const path = doc.$__fullPath(this.path);
64710
- const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
64711
- const pop = owner.populated(path, true);
64712
- let ret = value;
64713
- if (!doc.$__.populated ||
64714
- !doc.$__.populated[path] ||
64715
- !doc.$__.populated[path].options ||
64716
- !doc.$__.populated[path].options.options ||
64717
- !doc.$__.populated[path].options.options.lean) {
64718
- ret = new pop.options[populateModelSymbol](value);
64719
- ret.$__.wasPopulated = true;
64720
65077
  }
64721
65078
 
64722
- return ret;
65079
+ return this._castRef(value, doc, init);
64723
65080
  }
64724
65081
 
64725
65082
  let castObjectId;
@@ -64786,8 +65143,7 @@ function resetId(v) {
64786
65143
 
64787
65144
  module.exports = ObjectId;
64788
65145
 
64789
- }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
64790
- },{"../../../is-buffer/index.js":178,"../cast/objectid":191,"../helpers/symbols":251,"../options/SchemaObjectIdOptions":264,"../schematype":294,"../types/objectid":304,"../utils":306,"./../document":193}],286:[function(require,module,exports){
65146
+ },{"../cast/objectid":191,"../helpers/getConstructorName":230,"../options/SchemaObjectIdOptions":266,"../schematype":296,"../types/objectid":306,"../utils":308,"./../document":193}],288:[function(require,module,exports){
64791
65147
  (function (Buffer){(function (){
64792
65148
  /*!
64793
65149
  * Module requirements.
@@ -64829,7 +65185,7 @@ function _castNumber(path, num) {
64829
65185
  module.exports = handleBitwiseOperator;
64830
65186
 
64831
65187
  }).call(this)}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")})
64832
- },{"../../../../is-buffer/index.js":178,"../../error/cast":201}],287:[function(require,module,exports){
65188
+ },{"../../../../is-buffer/index.js":178,"../../error/cast":201}],289:[function(require,module,exports){
64833
65189
  'use strict';
64834
65190
 
64835
65191
  const castBoolean = require('../../cast/boolean');
@@ -64843,7 +65199,7 @@ module.exports = function(val) {
64843
65199
  return castBoolean(val, path);
64844
65200
  };
64845
65201
 
64846
- },{"../../cast/boolean":187}],288:[function(require,module,exports){
65202
+ },{"../../cast/boolean":187}],290:[function(require,module,exports){
64847
65203
  /*!
64848
65204
  * Module requirements.
64849
65205
  */
@@ -64952,7 +65308,7 @@ function _castMinMaxDistance(self, val) {
64952
65308
  }
64953
65309
  }
64954
65310
 
64955
- },{"../array":275,"./helpers":289}],289:[function(require,module,exports){
65311
+ },{"../array":277,"./helpers":291}],291:[function(require,module,exports){
64956
65312
  'use strict';
64957
65313
 
64958
65314
  /*!
@@ -64986,7 +65342,7 @@ function castArraysOfNumbers(arr, self) {
64986
65342
  });
64987
65343
  }
64988
65344
 
64989
- },{"../number":284}],290:[function(require,module,exports){
65345
+ },{"../number":286}],292:[function(require,module,exports){
64990
65346
  'use strict';
64991
65347
 
64992
65348
  const CastError = require('../../error/cast');
@@ -65027,7 +65383,7 @@ module.exports = function(val, path) {
65027
65383
  return val;
65028
65384
  };
65029
65385
 
65030
- },{"../../cast/boolean":187,"../../cast/string":192,"../../error/cast":201}],291:[function(require,module,exports){
65386
+ },{"../../cast/boolean":187,"../../cast/string":192,"../../error/cast":201}],293:[function(require,module,exports){
65031
65387
  'use strict';
65032
65388
 
65033
65389
  /*!
@@ -65049,8 +65405,7 @@ module.exports = function(val) {
65049
65405
  return val;
65050
65406
  };
65051
65407
 
65052
- },{}],292:[function(require,module,exports){
65053
- (function (Buffer){(function (){
65408
+ },{}],294:[function(require,module,exports){
65054
65409
  'use strict';
65055
65410
 
65056
65411
  /*!
@@ -65063,10 +65418,7 @@ const SchemaStringOptions = require('../options/SchemaStringOptions');
65063
65418
  const castString = require('../cast/string');
65064
65419
  const utils = require('../utils');
65065
65420
 
65066
- const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
65067
-
65068
65421
  const CastError = SchemaType.CastError;
65069
- let Document;
65070
65422
 
65071
65423
  /**
65072
65424
  * String SchemaType constructor.
@@ -65637,36 +65989,11 @@ SchemaString.prototype.checkRequired = function checkRequired(value, doc) {
65637
65989
 
65638
65990
  SchemaString.prototype.cast = function(value, doc, init) {
65639
65991
  if (SchemaType._isRef(this, value, doc, init)) {
65640
- // wait! we may need to cast this to a document
65641
-
65642
- if (value === null || value === undefined) {
65643
- return value;
65644
- }
65645
-
65646
- // lazy load
65647
- Document || (Document = require('./../document'));
65648
-
65649
- if (value instanceof Document) {
65650
- value.$__.wasPopulated = true;
65651
- return value;
65652
- }
65653
-
65654
- // setting a populated path
65655
65992
  if (typeof value === 'string') {
65656
65993
  return value;
65657
- } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
65658
- throw new CastError('string', value, this.path, null, this);
65659
65994
  }
65660
65995
 
65661
- // Handle the case where user directly sets a populated
65662
- // path to a plain object; cast to the Model used in
65663
- // the population query.
65664
- const path = doc.$__fullPath(this.path);
65665
- const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
65666
- const pop = owner.populated(path, true);
65667
- const ret = new pop.options[populateModelSymbol](value);
65668
- ret.$__.wasPopulated = true;
65669
- return ret;
65996
+ return this._castRef(value, doc, init);
65670
65997
  }
65671
65998
 
65672
65999
  let castString;
@@ -65752,14 +66079,13 @@ SchemaString.prototype.castForQuery = function($conditional, val) {
65752
66079
 
65753
66080
  module.exports = SchemaString;
65754
66081
 
65755
- }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
65756
- },{"../../../is-buffer/index.js":178,"../cast/string":192,"../error/index":203,"../helpers/symbols":251,"../options/SchemaStringOptions":266,"../schematype":294,"../utils":306,"./../document":193}],293:[function(require,module,exports){
66082
+ },{"../cast/string":192,"../error/index":203,"../options/SchemaStringOptions":268,"../schematype":296,"../utils":308}],295:[function(require,module,exports){
65757
66083
  'use strict';
65758
66084
 
65759
66085
  exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed');
65760
66086
 
65761
66087
  exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware');
65762
- },{}],294:[function(require,module,exports){
66088
+ },{}],296:[function(require,module,exports){
65763
66089
  (function (Buffer){(function (){
65764
66090
  'use strict';
65765
66091
 
@@ -65780,6 +66106,8 @@ const utils = require('./utils');
65780
66106
  const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol;
65781
66107
  const documentIsModified = require('./helpers/symbols').documentIsModified;
65782
66108
 
66109
+ const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
66110
+
65783
66111
  const CastError = MongooseError.CastError;
65784
66112
  const ValidatorError = MongooseError.ValidatorError;
65785
66113
 
@@ -65808,6 +66136,8 @@ function SchemaType(path, options, instance) {
65808
66136
  [];
65809
66137
  this.setters = [];
65810
66138
 
66139
+ this.splitPath();
66140
+
65811
66141
  options = options || {};
65812
66142
  const defaultOptions = this.constructor.defaultOptions || {};
65813
66143
  const defaultOptionsKeys = Object.keys(defaultOptions);
@@ -65882,11 +66212,27 @@ function SchemaType(path, options, instance) {
65882
66212
  }
65883
66213
 
65884
66214
  /*!
65885
- * ignore
66215
+ * The class that Mongoose uses internally to instantiate this SchemaType's `options` property.
65886
66216
  */
65887
66217
 
65888
66218
  SchemaType.prototype.OptionsConstructor = SchemaTypeOptions;
65889
66219
 
66220
+ /*!
66221
+ * ignore
66222
+ */
66223
+
66224
+ SchemaType.prototype.splitPath = function() {
66225
+ if (this._presplitPath != null) {
66226
+ return this._presplitPath;
66227
+ }
66228
+ if (this.path == null) {
66229
+ return undefined;
66230
+ }
66231
+
66232
+ this._presplitPath = this.path.indexOf('.') === -1 ? [this.path] : this.path.split('.');
66233
+ return this._presplitPath;
66234
+ };
66235
+
65890
66236
  /**
65891
66237
  * Get/set the function used to cast arbitrary values to this type.
65892
66238
  *
@@ -65953,6 +66299,19 @@ SchemaType.prototype.castFunction = function castFunction(caster) {
65953
66299
  return this._castFunction;
65954
66300
  };
65955
66301
 
66302
+ /**
66303
+ * The function that Mongoose calls to cast arbitrary values to this SchemaType.
66304
+ *
66305
+ * @param {Object} value value to cast
66306
+ * @param {Document} doc document that triggers the casting
66307
+ * @param {Boolean} init
66308
+ * @api public
66309
+ */
66310
+
66311
+ SchemaType.prototype.cast = function cast() {
66312
+ throw new Error('Base SchemaType class does not implement a `cast()` function');
66313
+ };
66314
+
65956
66315
  /**
65957
66316
  * Sets a default option for this schema type.
65958
66317
  *
@@ -66819,8 +67178,8 @@ SchemaType.prototype._applySetters = function(value, scope, init) {
66819
67178
  }
66820
67179
  const setters = this.setters;
66821
67180
 
66822
- for (const setter of utils.clone(setters).reverse()) {
66823
- v = setter.call(scope, v, this);
67181
+ for (let i = setters.length - 1; i >= 0; i--) {
67182
+ v = setters[i].call(scope, v, this);
66824
67183
  }
66825
67184
 
66826
67185
  return v;
@@ -66845,7 +67204,6 @@ SchemaType.prototype._castNullish = function _castNullish(v) {
66845
67204
 
66846
67205
  SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) {
66847
67206
  let v = this._applySetters(value, scope, init, priorVal, options);
66848
-
66849
67207
  if (v == null) {
66850
67208
  return this._castNullish(v);
66851
67209
  }
@@ -67177,11 +67535,54 @@ SchemaType._isRef = function(self, value, doc, init) {
67177
67535
  ) {
67178
67536
  return true;
67179
67537
  }
67538
+
67539
+ return init;
67180
67540
  }
67181
67541
 
67182
67542
  return false;
67183
67543
  };
67184
67544
 
67545
+ /*!
67546
+ * ignore
67547
+ */
67548
+
67549
+ SchemaType.prototype._castRef = function _castRef(value, doc, init) {
67550
+ if (value == null) {
67551
+ return value;
67552
+ }
67553
+
67554
+ if (value.$__ != null) {
67555
+ value.$__.wasPopulated = true;
67556
+ return value;
67557
+ }
67558
+
67559
+ // setting a populated path
67560
+ if (Buffer.isBuffer(value) || !utils.isObject(value)) {
67561
+ if (init) {
67562
+ return value;
67563
+ }
67564
+ throw new CastError(this.instance, value, this.path, null, this);
67565
+ }
67566
+
67567
+ // Handle the case where user directly sets a populated
67568
+ // path to a plain object; cast to the Model used in
67569
+ // the population query.
67570
+ const path = doc.$__fullPath(this.path);
67571
+ const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
67572
+ const pop = owner.populated(path, true);
67573
+ let ret = value;
67574
+ if (!doc.$__.populated ||
67575
+ !doc.$__.populated[path] ||
67576
+ !doc.$__.populated[path].options ||
67577
+ !doc.$__.populated[path].options.options ||
67578
+ !doc.$__.populated[path].options.options.lean) {
67579
+ ret = new pop.options[populateModelSymbol](value);
67580
+ ret.$__.wasPopulated = true;
67581
+ }
67582
+
67583
+ return ret;
67584
+ };
67585
+
67185
67586
  /*!
67186
67587
  * ignore
67187
67588
  */
@@ -67360,7 +67761,7 @@ exports.CastError = CastError;
67360
67761
  exports.ValidatorError = ValidatorError;
67361
67762
 
67362
67763
  }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
67363
- },{"../../is-buffer/index.js":178,"./error/index":203,"./helpers/get":228,"./helpers/immediate":230,"./helpers/schematype/handleImmutable":249,"./helpers/symbols":251,"./options/SchemaTypeOptions":267,"./schema/operators/exists":287,"./schema/operators/type":291,"./utils":306,"util":331}],295:[function(require,module,exports){
67764
+ },{"../../is-buffer/index.js":178,"./error/index":203,"./helpers/get":229,"./helpers/immediate":232,"./helpers/schematype/handleImmutable":251,"./helpers/symbols":253,"./options/SchemaTypeOptions":269,"./schema/operators/exists":289,"./schema/operators/type":293,"./utils":308,"util":333}],297:[function(require,module,exports){
67364
67765
 
67365
67766
  /*!
67366
67767
  * Module dependencies.
@@ -67542,7 +67943,7 @@ StateMachine.prototype.map = function map() {
67542
67943
  return this.map.apply(this, arguments);
67543
67944
  };
67544
67945
 
67545
- },{"./utils":306}],296:[function(require,module,exports){
67946
+ },{"./utils":308}],298:[function(require,module,exports){
67546
67947
  /*!
67547
67948
  * Module dependencies.
67548
67949
  */
@@ -67550,7 +67951,6 @@ StateMachine.prototype.map = function map() {
67550
67951
  'use strict';
67551
67952
 
67552
67953
  const CoreMongooseArray = require('./core_array');
67553
- const Document = require('../document');
67554
67954
 
67555
67955
  const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
67556
67956
  const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
@@ -67575,28 +67975,44 @@ const _basePush = Array.prototype.push;
67575
67975
  */
67576
67976
 
67577
67977
  function MongooseArray(values, path, doc, schematype) {
67578
- const arr = new CoreMongooseArray();
67579
- arr[arrayAtomicsSymbol] = {};
67978
+ let arr;
67580
67979
 
67581
67980
  if (Array.isArray(values)) {
67582
67981
  const len = values.length;
67583
- for (let i = 0; i < len; ++i) {
67584
- _basePush.call(arr, values[i]);
67982
+
67983
+ // Perf optimizations for small arrays: much faster to use `...` than `for` + `push`,
67984
+ // but large arrays may cause stack overflows. And for arrays of length 0/1, just
67985
+ // modifying the array is faster. Seems small, but adds up when you have a document
67986
+ // with thousands of nested arrays.
67987
+ if (len === 0) {
67988
+ arr = new CoreMongooseArray();
67989
+ } else if (len === 1) {
67990
+ arr = new CoreMongooseArray(1);
67991
+ arr[0] = values[0];
67992
+ } else if (len < 10000) {
67993
+ arr = new CoreMongooseArray();
67994
+ _basePush.apply(arr, values);
67995
+ } else {
67996
+ arr = new CoreMongooseArray();
67997
+ for (let i = 0; i < len; ++i) {
67998
+ _basePush.call(arr, values[i]);
67999
+ }
67585
68000
  }
67586
68001
 
67587
68002
  if (values[arrayAtomicsSymbol] != null) {
67588
68003
  arr[arrayAtomicsSymbol] = values[arrayAtomicsSymbol];
67589
68004
  }
68005
+ } else {
68006
+ arr = new CoreMongooseArray();
67590
68007
  }
67591
68008
 
67592
68009
  arr[arrayPathSymbol] = path;
67593
- arr[arraySchemaSymbol] = void 0;
67594
68010
 
67595
68011
  // Because doc comes from the context of another function, doc === global
67596
68012
  // can happen if there was a null somewhere up the chain (see #3020)
67597
68013
  // RB Jun 17, 2015 updated to check for presence of expected paths instead
67598
68014
  // to make more proof against unusual node environments
67599
- if (doc && doc instanceof Document) {
68015
+ if (doc != null && doc.$__ != null) {
67600
68016
  arr[arrayParentSymbol] = doc;
67601
68017
  arr[arraySchemaSymbol] = schematype || doc.schema.path(path);
67602
68018
  }
@@ -67610,7 +68026,7 @@ function MongooseArray(values, path, doc, schematype) {
67610
68026
 
67611
68027
  module.exports = exports = MongooseArray;
67612
68028
 
67613
- },{"../document":193,"../helpers/symbols":251,"./core_array":298}],297:[function(require,module,exports){
68029
+ },{"../helpers/symbols":253,"./core_array":300}],299:[function(require,module,exports){
67614
68030
  /*!
67615
68031
  * Module dependencies.
67616
68032
  */
@@ -67888,7 +68304,7 @@ MongooseBuffer.Binary = Binary;
67888
68304
 
67889
68305
  module.exports = MongooseBuffer;
67890
68306
 
67891
- },{"../driver":195,"../utils":306,"safe-buffer":326}],298:[function(require,module,exports){
68307
+ },{"../driver":195,"../utils":308,"safe-buffer":328}],300:[function(require,module,exports){
67892
68308
  (function (Buffer){(function (){
67893
68309
  'use strict';
67894
68310
 
@@ -67986,7 +68402,7 @@ class CoreMongooseArray extends Array {
67986
68402
  */
67987
68403
 
67988
68404
  $atomics() {
67989
- return this[arrayAtomicsSymbol];
68405
+ return this[arrayAtomicsSymbol] || {};
67990
68406
  }
67991
68407
 
67992
68408
  /*!
@@ -68140,8 +68556,8 @@ class CoreMongooseArray extends Array {
68140
68556
 
68141
68557
  // gh-2399
68142
68558
  // we should cast model only when it's not a discriminator
68143
- const isDisc = value.schema && value.schema.discriminatorMapping &&
68144
- value.schema.discriminatorMapping.key !== undefined;
68559
+ const isDisc = value.$__schema && value.$__schema.discriminatorMapping &&
68560
+ value.$__schema.discriminatorMapping.key !== undefined;
68145
68561
  if (!isDisc) {
68146
68562
  value = new Model(value);
68147
68563
  }
@@ -68220,6 +68636,8 @@ class CoreMongooseArray extends Array {
68220
68636
  return this;
68221
68637
  }
68222
68638
 
68639
+ this[arrayAtomicsSymbol] || (this[arrayAtomicsSymbol] = {});
68640
+
68223
68641
  const atomics = this[arrayAtomicsSymbol];
68224
68642
 
68225
68643
  // reset pop/shift after save
@@ -68860,7 +69278,7 @@ function _checkManualPopulation(arr, docs) {
68860
69278
  module.exports = CoreMongooseArray;
68861
69279
 
68862
69280
  }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
68863
- },{"../../../is-buffer/index.js":178,"../document":193,"../error/mongooseError":206,"../helpers/document/cleanModifiedSubpaths":224,"../helpers/get":228,"../helpers/symbols":251,"../options":256,"../utils":306,"./embedded":301,"./objectid":304,"util":331}],299:[function(require,module,exports){
69281
+ },{"../../../is-buffer/index.js":178,"../document":193,"../error/mongooseError":206,"../helpers/document/cleanModifiedSubpaths":225,"../helpers/get":229,"../helpers/symbols":253,"../options":258,"../utils":308,"./embedded":303,"./objectid":306,"util":333}],301:[function(require,module,exports){
68864
69282
  /**
68865
69283
  * ObjectId type constructor
68866
69284
  *
@@ -68875,7 +69293,7 @@ module.exports = CoreMongooseArray;
68875
69293
 
68876
69294
  module.exports = require('../driver').get().Decimal128;
68877
69295
 
68878
- },{"../driver":195}],300:[function(require,module,exports){
69296
+ },{"../driver":195}],302:[function(require,module,exports){
68879
69297
  (function (Buffer){(function (){
68880
69298
  'use strict';
68881
69299
 
@@ -68975,7 +69393,7 @@ class CoreDocumentArray extends CoreMongooseArray {
68975
69393
  Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
68976
69394
  Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
68977
69395
  } else {
68978
- const constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]);
69396
+ const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]);
68979
69397
  if (constructorByValue) {
68980
69398
  Constructor = constructorByValue;
68981
69399
  }
@@ -69168,7 +69586,7 @@ class CoreDocumentArray extends CoreMongooseArray {
69168
69586
  Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
69169
69587
  Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
69170
69588
  } else {
69171
- const constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]);
69589
+ const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]);
69172
69590
  if (constructorByValue) {
69173
69591
  Constructor = constructorByValue;
69174
69592
  }
@@ -69327,7 +69745,7 @@ function MongooseDocumentArray(values, path, doc) {
69327
69745
  module.exports = MongooseDocumentArray;
69328
69746
 
69329
69747
  }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
69330
- },{"../../../is-buffer/index.js":178,"../cast/objectid":191,"../document":193,"../helpers/discriminator/getDiscriminatorByValue":222,"../helpers/symbols":251,"../options":256,"../utils":306,"./core_array":298,"./objectid":304,"util":331}],301:[function(require,module,exports){
69748
+ },{"../../../is-buffer/index.js":178,"../cast/objectid":191,"../document":193,"../helpers/discriminator/getDiscriminatorByValue":223,"../helpers/symbols":253,"../options":258,"../utils":308,"./core_array":300,"./objectid":306,"util":333}],303:[function(require,module,exports){
69331
69749
  /* eslint no-func-assign: 1 */
69332
69750
 
69333
69751
  /*!
@@ -69727,7 +70145,7 @@ EmbeddedDocument.prototype.ownerDocument = function() {
69727
70145
 
69728
70146
  EmbeddedDocument.prototype.$__fullPath = function(path) {
69729
70147
  if (!this.$__.fullPath) {
69730
- let parent = this; // eslint-disable-line consistent-this
70148
+ let parent = this;
69731
70149
  if (!parent[documentArrayParent]) {
69732
70150
  return path;
69733
70151
  }
@@ -69789,7 +70207,7 @@ EmbeddedDocument.prototype.parentArray = function() {
69789
70207
 
69790
70208
  module.exports = EmbeddedDocument;
69791
70209
 
69792
- },{"../document_provider":194,"../error/validation":214,"../helpers/get":228,"../helpers/immediate":230,"../helpers/promiseOrCallback":240,"../helpers/symbols":251,"../options":256,"events":176,"util":331}],302:[function(require,module,exports){
70210
+ },{"../document_provider":194,"../error/validation":214,"../helpers/get":229,"../helpers/immediate":232,"../helpers/promiseOrCallback":242,"../helpers/symbols":253,"../options":258,"events":176,"util":333}],304:[function(require,module,exports){
69793
70211
 
69794
70212
  /*!
69795
70213
  * Module exports.
@@ -69811,13 +70229,15 @@ exports.Map = require('./map');
69811
70229
 
69812
70230
  exports.Subdocument = require('./subdocument');
69813
70231
 
69814
- },{"./array":296,"./buffer":297,"./decimal128":299,"./documentarray":300,"./embedded":301,"./map":303,"./objectid":304,"./subdocument":305}],303:[function(require,module,exports){
70232
+ },{"./array":298,"./buffer":299,"./decimal128":301,"./documentarray":302,"./embedded":303,"./map":305,"./objectid":306,"./subdocument":307}],305:[function(require,module,exports){
69815
70233
  'use strict';
69816
70234
 
69817
70235
  const Mixed = require('../schema/mixed');
69818
70236
  const ObjectId = require('./objectid');
70237
+ const clone = require('../helpers/clone');
69819
70238
  const deepEqual = require('../utils').deepEqual;
69820
70239
  const get = require('../helpers/get');
70240
+ const getConstructorName = require('../helpers/getConstructorName');
69821
70241
  const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
69822
70242
  const util = require('util');
69823
70243
  const specialProperties = require('../helpers/specialProperties');
@@ -69830,7 +70250,7 @@ const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
69830
70250
 
69831
70251
  class MongooseMap extends Map {
69832
70252
  constructor(v, path, doc, schemaType) {
69833
- if (v != null && v.constructor.name === 'Object') {
70253
+ if (getConstructorName(v) === 'Object') {
69834
70254
  v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []);
69835
70255
  }
69836
70256
  super(v);
@@ -69947,7 +70367,7 @@ class MongooseMap extends Map {
69947
70367
  const ret = {};
69948
70368
  const keys = this.keys();
69949
70369
  for (const key of keys) {
69950
- ret[key] = this.get(key);
70370
+ ret[key] = clone(this.get(key));
69951
70371
  }
69952
70372
  return ret;
69953
70373
  }
@@ -70051,7 +70471,7 @@ function checkValidKey(key) {
70051
70471
 
70052
70472
  module.exports = MongooseMap;
70053
70473
 
70054
- },{"../helpers/document/handleSpreadDoc":227,"../helpers/get":228,"../helpers/specialProperties":250,"../helpers/symbols":251,"../schema/mixed":283,"../utils":306,"./objectid":304,"util":331}],304:[function(require,module,exports){
70474
+ },{"../helpers/clone":218,"../helpers/document/handleSpreadDoc":228,"../helpers/get":229,"../helpers/getConstructorName":230,"../helpers/specialProperties":252,"../helpers/symbols":253,"../schema/mixed":285,"../utils":308,"./objectid":306,"util":333}],306:[function(require,module,exports){
70055
70475
  /**
70056
70476
  * ObjectId type constructor
70057
70477
  *
@@ -70083,7 +70503,7 @@ ObjectId.prototype[objectIdSymbol] = true;
70083
70503
 
70084
70504
  module.exports = ObjectId;
70085
70505
 
70086
- },{"../driver":195,"../helpers/symbols":251}],305:[function(require,module,exports){
70506
+ },{"../driver":195,"../helpers/symbols":253}],307:[function(require,module,exports){
70087
70507
  'use strict';
70088
70508
 
70089
70509
  const Document = require('../document');
@@ -70111,9 +70531,9 @@ function Subdocument(value, fields, parent, skipId, options) {
70111
70531
  let initedPaths = null;
70112
70532
  if (hasPriorDoc) {
70113
70533
  this._doc = Object.assign({}, options.priorDoc._doc);
70114
- delete this._doc[this.schema.options.discriminatorKey];
70534
+ delete this._doc[this.$__schema.options.discriminatorKey];
70115
70535
  initedPaths = Object.keys(options.priorDoc._doc || {}).
70116
- filter(key => key !== this.schema.options.discriminatorKey);
70536
+ filter(key => key !== this.$__schema.options.discriminatorKey);
70117
70537
  }
70118
70538
  if (parent != null) {
70119
70539
  // If setting a nested path, should copy isNew from parent re: gh-7048
@@ -70129,7 +70549,7 @@ function Subdocument(value, fields, parent, skipId, options) {
70129
70549
  if (!this.$__.activePaths.states.modify[key] &&
70130
70550
  !this.$__.activePaths.states.default[key] &&
70131
70551
  !this.$__.$setCalled.has(key)) {
70132
- const schematype = this.schema.path(key);
70552
+ const schematype = this.$__schema.path(key);
70133
70553
  const def = schematype == null ? void 0 : schematype.getDefault(this);
70134
70554
  if (def === void 0) {
70135
70555
  delete this._doc[key];
@@ -70386,7 +70806,7 @@ function registerRemoveListener(sub) {
70386
70806
  owner.on('remove', emitRemove);
70387
70807
  }
70388
70808
 
70389
- },{"../document":193,"../helpers/immediate":230,"../helpers/promiseOrCallback":240,"../helpers/symbols":251,"../options":256}],306:[function(require,module,exports){
70809
+ },{"../document":193,"../helpers/immediate":232,"../helpers/promiseOrCallback":242,"../helpers/symbols":253,"../options":258}],308:[function(require,module,exports){
70390
70810
  (function (process){(function (){
70391
70811
  'use strict';
70392
70812
 
@@ -70402,11 +70822,13 @@ const Decimal = require('./types/decimal128');
70402
70822
  const ObjectId = require('./types/objectid');
70403
70823
  const PopulateOptions = require('./options/PopulateOptions');
70404
70824
  const clone = require('./helpers/clone');
70825
+ const immediate = require('./helpers/immediate');
70405
70826
  const isObject = require('./helpers/isObject');
70406
70827
  const isBsonType = require('./helpers/isBsonType');
70407
70828
  const getFunctionName = require('./helpers/getFunctionName');
70408
70829
  const isMongooseObject = require('./helpers/isMongooseObject');
70409
70830
  const promiseOrCallback = require('./helpers/promiseOrCallback');
70831
+ const schemaMerge = require('./helpers/schema/merge');
70410
70832
  const specialProperties = require('./helpers/specialProperties');
70411
70833
 
70412
70834
  let Document;
@@ -70672,7 +71094,7 @@ exports.merge = function merge(to, from, options, path) {
70672
71094
  continue;
70673
71095
  } else if (from[key].instanceOfSchema) {
70674
71096
  if (to[key].instanceOfSchema) {
70675
- to[key].add(from[key].clone());
71097
+ schemaMerge(to[key], from[key].clone(), options.isDiscriminatorSchemaMerge);
70676
71098
  } else {
70677
71099
  to[key] = from[key].clone();
70678
71100
  }
@@ -70829,7 +71251,7 @@ exports.tick = function tick(callback) {
70829
71251
  } catch (err) {
70830
71252
  // only nextTick on err to get out of
70831
71253
  // the event loop and avoid state corruption.
70832
- process.nextTick(function() {
71254
+ immediate(function() {
70833
71255
  throw err;
70834
71256
  });
70835
71257
  }
@@ -71145,23 +71567,23 @@ exports.isArrayIndex = function(val) {
71145
71567
  */
71146
71568
 
71147
71569
  exports.array.unique = function(arr) {
71148
- const primitives = {};
71149
- const ids = {};
71570
+ const primitives = new Set();
71571
+ const ids = new Set();
71150
71572
  const ret = [];
71151
71573
 
71152
71574
  for (const item of arr) {
71153
71575
  if (typeof item === 'number' || typeof item === 'string' || item == null) {
71154
- if (primitives[item]) {
71576
+ if (primitives.has(item)) {
71155
71577
  continue;
71156
71578
  }
71157
71579
  ret.push(item);
71158
- primitives[item] = true;
71580
+ primitives.add(item);
71159
71581
  } else if (item instanceof ObjectId) {
71160
- if (ids[item.toString()]) {
71582
+ if (ids.has(item.toString())) {
71161
71583
  continue;
71162
71584
  }
71163
71585
  ret.push(item);
71164
- ids[item.toString()] = true;
71586
+ ids.add(item.toString());
71165
71587
  } else {
71166
71588
  ret.push(item);
71167
71589
  }
@@ -71311,8 +71733,23 @@ exports.getOption = function(name) {
71311
71733
 
71312
71734
  exports.noop = function() {};
71313
71735
 
71736
+ exports.errorToPOJO = function errorToPOJO(error) {
71737
+ const isError = error instanceof Error;
71738
+ if (!isError) {
71739
+ throw new Error('`error` must be `instanceof Error`.');
71740
+ }
71741
+
71742
+ const ret = {};
71743
+ for (const properyName of Object.getOwnPropertyNames(error)) {
71744
+ ret[properyName] = error[properyName];
71745
+ }
71746
+ return ret;
71747
+ };
71748
+
71749
+ exports.nodeMajorVersion = parseInt(process.versions.node.split('.')[0], 10);
71750
+
71314
71751
  }).call(this)}).call(this,require('_process'))
71315
- },{"./document":193,"./helpers/clone":218,"./helpers/getFunctionName":229,"./helpers/isBsonType":231,"./helpers/isMongooseObject":232,"./helpers/isObject":233,"./helpers/promiseOrCallback":240,"./helpers/specialProperties":250,"./options/PopulateOptions":257,"./types/decimal128":299,"./types/objectid":304,"_process":324,"mpath":309,"ms":308,"safe-buffer":326,"sliced":327}],307:[function(require,module,exports){
71752
+ },{"./document":193,"./helpers/clone":218,"./helpers/getFunctionName":231,"./helpers/immediate":232,"./helpers/isBsonType":233,"./helpers/isMongooseObject":234,"./helpers/isObject":235,"./helpers/promiseOrCallback":242,"./helpers/schema/merge":250,"./helpers/specialProperties":252,"./options/PopulateOptions":259,"./types/decimal128":301,"./types/objectid":306,"_process":326,"mpath":311,"ms":310,"safe-buffer":328,"sliced":329}],309:[function(require,module,exports){
71316
71753
  'use strict';
71317
71754
 
71318
71755
  const utils = require('./utils');
@@ -71490,7 +71927,7 @@ VirtualType.prototype.applySetters = function(value, doc) {
71490
71927
 
71491
71928
  module.exports = VirtualType;
71492
71929
 
71493
- },{"./utils":306}],308:[function(require,module,exports){
71930
+ },{"./utils":308}],310:[function(require,module,exports){
71494
71931
  /**
71495
71932
  * Helpers.
71496
71933
  */
@@ -71654,12 +72091,12 @@ function plural(ms, msAbs, n, name) {
71654
72091
  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
71655
72092
  }
71656
72093
 
71657
- },{}],309:[function(require,module,exports){
72094
+ },{}],311:[function(require,module,exports){
71658
72095
  'use strict';
71659
72096
 
71660
72097
  module.exports = exports = require('./lib');
71661
72098
 
71662
- },{"./lib":310}],310:[function(require,module,exports){
72099
+ },{"./lib":312}],312:[function(require,module,exports){
71663
72100
  /* eslint strict:off */
71664
72101
  /* eslint no-var: off */
71665
72102
  /* eslint no-redeclare: off */
@@ -71726,6 +72163,9 @@ exports.get = function(path, o, special, map) {
71726
72163
 
71727
72164
  for (var i = 0; i < parts.length; ++i) {
71728
72165
  part = parts[i];
72166
+ if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') {
72167
+ throw new TypeError('Each segment of path to `get()` must be a string or number, got ' + typeof parts[i]);
72168
+ }
71729
72169
 
71730
72170
  if (Array.isArray(obj) && !/^\d+$/.test(part)) {
71731
72171
  // reading a property from the array items
@@ -71774,6 +72214,9 @@ exports.has = function(path, o) {
71774
72214
  var len = parts.length;
71775
72215
  var cur = o;
71776
72216
  for (var i = 0; i < len; ++i) {
72217
+ if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') {
72218
+ throw new TypeError('Each segment of path to `has()` must be a string or number, got ' + typeof parts[i]);
72219
+ }
71777
72220
  if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) {
71778
72221
  return false;
71779
72222
  }
@@ -71805,6 +72248,9 @@ exports.unset = function(path, o) {
71805
72248
  if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) {
71806
72249
  return false;
71807
72250
  }
72251
+ if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') {
72252
+ throw new TypeError('Each segment of path to `unset()` must be a string or number, got ' + typeof parts[i]);
72253
+ }
71808
72254
  // Disallow any updates to __proto__ or special properties.
71809
72255
  if (ignoreProperties.indexOf(parts[i]) !== -1) {
71810
72256
  return false;
@@ -71855,6 +72301,9 @@ exports.set = function(path, val, o, special, map, _copying) {
71855
72301
  if (null == o) return;
71856
72302
 
71857
72303
  for (var i = 0; i < parts.length; ++i) {
72304
+ if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') {
72305
+ throw new TypeError('Each segment of path to `set()` must be a string or number, got ' + typeof parts[i]);
72306
+ }
71858
72307
  // Silently ignore any updates to `__proto__`, these are potentially
71859
72308
  // dangerous if using mpath with unsanitized data.
71860
72309
  if (ignoreProperties.indexOf(parts[i]) !== -1) {
@@ -71974,7 +72423,7 @@ function _setArray(obj, val, part, lookup, special, map) {
71974
72423
  function K(v) {
71975
72424
  return v;
71976
72425
  }
71977
- },{"./stringToParts":311}],311:[function(require,module,exports){
72426
+ },{"./stringToParts":313}],313:[function(require,module,exports){
71978
72427
  'use strict';
71979
72428
 
71980
72429
  module.exports = function stringToParts(str) {
@@ -72023,7 +72472,7 @@ module.exports = function stringToParts(str) {
72023
72472
 
72024
72473
  return result;
72025
72474
  };
72026
- },{}],312:[function(require,module,exports){
72475
+ },{}],314:[function(require,module,exports){
72027
72476
  'use strict';
72028
72477
 
72029
72478
  /**
@@ -72071,7 +72520,7 @@ function notImplemented(method) {
72071
72520
  };
72072
72521
  }
72073
72522
 
72074
- },{}],313:[function(require,module,exports){
72523
+ },{}],315:[function(require,module,exports){
72075
72524
  'use strict';
72076
72525
 
72077
72526
  var env = require('../env');
@@ -72086,7 +72535,7 @@ module.exports =
72086
72535
  require('./collection');
72087
72536
 
72088
72537
 
72089
- },{"../env":315,"./collection":312,"./node":314}],314:[function(require,module,exports){
72538
+ },{"../env":317,"./collection":314,"./node":316}],316:[function(require,module,exports){
72090
72539
  'use strict';
72091
72540
 
72092
72541
  /**
@@ -72239,7 +72688,7 @@ NodeCollection.prototype.findCursor = function(match, findOptions) {
72239
72688
 
72240
72689
  module.exports = exports = NodeCollection;
72241
72690
 
72242
- },{"../utils":318,"./collection":312}],315:[function(require,module,exports){
72691
+ },{"../utils":320,"./collection":314}],317:[function(require,module,exports){
72243
72692
  (function (process,global,Buffer){(function (){
72244
72693
  'use strict';
72245
72694
 
@@ -72265,7 +72714,7 @@ exports.type = exports.isNode ? 'node'
72265
72714
  : 'unknown';
72266
72715
 
72267
72716
  }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
72268
- },{"_process":324,"buffer":128}],316:[function(require,module,exports){
72717
+ },{"_process":326,"buffer":128}],318:[function(require,module,exports){
72269
72718
  'use strict';
72270
72719
 
72271
72720
  /**
@@ -75519,7 +75968,7 @@ module.exports = exports = Query;
75519
75968
  // TODO
75520
75969
  // test utils
75521
75970
 
75522
- },{"./collection":313,"./collection/collection":312,"./env":315,"./permissions":317,"./utils":318,"assert":102,"bluebird":107,"debug":319,"sliced":327,"util":331}],317:[function(require,module,exports){
75971
+ },{"./collection":315,"./collection/collection":314,"./env":317,"./permissions":319,"./utils":320,"assert":102,"bluebird":107,"debug":321,"sliced":329,"util":333}],319:[function(require,module,exports){
75523
75972
  'use strict';
75524
75973
 
75525
75974
  var denied = exports;
@@ -75609,7 +76058,7 @@ denied.count.maxScan =
75609
76058
  denied.count.snapshot =
75610
76059
  denied.count.tailable = true;
75611
76060
 
75612
- },{}],318:[function(require,module,exports){
76061
+ },{}],320:[function(require,module,exports){
75613
76062
  (function (process,setImmediate){(function (){
75614
76063
  'use strict';
75615
76064
 
@@ -75783,6 +76232,9 @@ exports.mergeClone = function mergeClone(to, from) {
75783
76232
 
75784
76233
  while (i--) {
75785
76234
  key = keys[i];
76235
+ if (specialProperties.indexOf(key) !== -1) {
76236
+ continue;
76237
+ }
75786
76238
  if ('undefined' === typeof to[key]) {
75787
76239
  to[key] = clone(from[key]);
75788
76240
  } else {
@@ -75973,7 +76425,7 @@ exports.isArgumentsObject = function(v) {
75973
76425
  };
75974
76426
 
75975
76427
  }).call(this)}).call(this,require('_process'),require("timers").setImmediate)
75976
- },{"_process":324,"regexp-clone":325,"safe-buffer":321,"timers":328}],319:[function(require,module,exports){
76428
+ },{"_process":326,"regexp-clone":327,"safe-buffer":323,"timers":330}],321:[function(require,module,exports){
75977
76429
  (function (process){(function (){
75978
76430
  /**
75979
76431
  * This is the web browser implementation of `debug()`.
@@ -76172,7 +76624,7 @@ function localstorage() {
76172
76624
  }
76173
76625
 
76174
76626
  }).call(this)}).call(this,require('_process'))
76175
- },{"./debug":320,"_process":324}],320:[function(require,module,exports){
76627
+ },{"./debug":322,"_process":326}],322:[function(require,module,exports){
76176
76628
 
76177
76629
  /**
76178
76630
  * This is the common logic for both the Node.js and web browser
@@ -76399,7 +76851,7 @@ function coerce(val) {
76399
76851
  return val;
76400
76852
  }
76401
76853
 
76402
- },{"ms":322}],321:[function(require,module,exports){
76854
+ },{"ms":324}],323:[function(require,module,exports){
76403
76855
  /* eslint-disable node/no-deprecated-api */
76404
76856
  var buffer = require('buffer')
76405
76857
  var Buffer = buffer.Buffer
@@ -76463,7 +76915,7 @@ SafeBuffer.allocUnsafeSlow = function (size) {
76463
76915
  return buffer.SlowBuffer(size)
76464
76916
  }
76465
76917
 
76466
- },{"buffer":128}],322:[function(require,module,exports){
76918
+ },{"buffer":128}],324:[function(require,module,exports){
76467
76919
  /**
76468
76920
  * Helpers.
76469
76921
  */
@@ -76617,7 +77069,7 @@ function plural(ms, n, name) {
76617
77069
  return Math.ceil(ms / n) + ' ' + name + 's';
76618
77070
  }
76619
77071
 
76620
- },{}],323:[function(require,module,exports){
77072
+ },{}],325:[function(require,module,exports){
76621
77073
  /*
76622
77074
  object-assign
76623
77075
  (c) Sindre Sorhus
@@ -76709,7 +77161,7 @@ module.exports = shouldUseNative() ? Object.assign : function (target, source) {
76709
77161
  return to;
76710
77162
  };
76711
77163
 
76712
- },{}],324:[function(require,module,exports){
77164
+ },{}],326:[function(require,module,exports){
76713
77165
  // shim for using process in browser
76714
77166
  var process = module.exports = {};
76715
77167
 
@@ -76895,7 +77347,7 @@ process.chdir = function (dir) {
76895
77347
  };
76896
77348
  process.umask = function() { return 0; };
76897
77349
 
76898
- },{}],325:[function(require,module,exports){
77350
+ },{}],327:[function(require,module,exports){
76899
77351
 
76900
77352
  const toString = Object.prototype.toString;
76901
77353
 
@@ -76924,7 +77376,7 @@ module.exports = exports = function (regexp) {
76924
77376
  }
76925
77377
 
76926
77378
 
76927
- },{}],326:[function(require,module,exports){
77379
+ },{}],328:[function(require,module,exports){
76928
77380
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
76929
77381
  /* eslint-disable node/no-deprecated-api */
76930
77382
  var buffer = require('buffer')
@@ -76991,7 +77443,7 @@ SafeBuffer.allocUnsafeSlow = function (size) {
76991
77443
  return buffer.SlowBuffer(size)
76992
77444
  }
76993
77445
 
76994
- },{"buffer":128}],327:[function(require,module,exports){
77446
+ },{"buffer":128}],329:[function(require,module,exports){
76995
77447
 
76996
77448
  /**
76997
77449
  * An Array.prototype.slice.call(arguments) alternative
@@ -77026,7 +77478,7 @@ module.exports = function (args, slice, sliceEnd) {
77026
77478
  }
77027
77479
 
77028
77480
 
77029
- },{}],328:[function(require,module,exports){
77481
+ },{}],330:[function(require,module,exports){
77030
77482
  (function (setImmediate,clearImmediate){(function (){
77031
77483
  var nextTick = require('process/browser.js').nextTick;
77032
77484
  var apply = Function.prototype.apply;
@@ -77105,10 +77557,10 @@ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate :
77105
77557
  delete immediateIds[id];
77106
77558
  };
77107
77559
  }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
77108
- },{"process/browser.js":324,"timers":328}],329:[function(require,module,exports){
77560
+ },{"process/browser.js":326,"timers":330}],331:[function(require,module,exports){
77109
77561
  arguments[4][103][0].apply(exports,arguments)
77110
- },{"dup":103}],330:[function(require,module,exports){
77562
+ },{"dup":103}],332:[function(require,module,exports){
77111
77563
  arguments[4][104][0].apply(exports,arguments)
77112
- },{"dup":104}],331:[function(require,module,exports){
77564
+ },{"dup":104}],333:[function(require,module,exports){
77113
77565
  arguments[4][105][0].apply(exports,arguments)
77114
- },{"./support/isBuffer":330,"_process":324,"dup":105,"inherits":329}]},{},[87]);
77566
+ },{"./support/isBuffer":332,"_process":326,"dup":105,"inherits":331}]},{},[87]);