mongoose 9.11.4 → 9.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/document.js CHANGED
@@ -9,7 +9,6 @@ const EventEmitter = require('events').EventEmitter;
9
9
  const InternalCache = require('./internal');
10
10
  const MongooseBuffer = require('./types/buffer');
11
11
  const MongooseError = require('./error/index');
12
- const MixedSchema = require('./schema/mixed');
13
12
  const ModifiedPathsSnapshot = require('./modifiedPathsSnapshot');
14
13
  const ObjectExpectedError = require('./error/objectExpected');
15
14
  const ObjectParameterError = require('./error/objectParameter');
@@ -93,7 +92,11 @@ function Document(obj, fields, options) {
93
92
  if (typeof options === 'boolean') {
94
93
  throw new Error('The skipId parameter has been removed. Use { skipId: true } in the options parameter instead.');
95
94
  }
96
- options = options == null ? {} : Object.assign({}, options);
95
+ // The constructor only reads from `options`. `$set()` gets its own copy below
96
+ // because it may modify the options it receives.
97
+ if (options == null) {
98
+ options = {};
99
+ }
97
100
  let skipId = options.skipId;
98
101
 
99
102
  this.$__ = new InternalCache();
@@ -105,6 +108,7 @@ function Document(obj, fields, options) {
105
108
  fields;
106
109
 
107
110
  this.$__setSchema(_schema);
111
+ options = Object.assign({}, options);
108
112
  fields = options;
109
113
  skipId = options.skipId;
110
114
  }
@@ -175,11 +179,12 @@ function Document(obj, fields, options) {
175
179
  }
176
180
  }
177
181
  if (obj) {
182
+ const setOptions = Object.assign({}, options);
178
183
  // Skip set hooks
179
184
  if (this.$__original_set) {
180
- this.$__original_set(obj, undefined, true, options);
185
+ this.$__original_set(obj, undefined, true, setOptions);
181
186
  } else {
182
- this.$set(obj, undefined, true, options);
187
+ this.$set(obj, undefined, true, setOptions);
183
188
  }
184
189
 
185
190
  if (obj.$__ != null && obj instanceof Document) {
@@ -866,9 +871,11 @@ function init(self, obj, doc, opts, prefix) {
866
871
  doc[i] = value;
867
872
  }
868
873
  }
869
- // mark as hydrated
870
- if (!self.$isModified(path)) {
871
- self.$__.activePaths.init(path);
874
+ // mark as hydrated. Skip `$isModified()` if no paths are modified, which
875
+ // is the common case when loading a document from the db.
876
+ const activePaths = self.$__.activePaths;
877
+ if (activePaths.states.modify == null || !self.$isModified(path)) {
878
+ activePaths.init(path);
872
879
  }
873
880
  }
874
881
  }
@@ -1106,141 +1113,105 @@ Document.prototype.$set = function $set(path, val, type, options) {
1106
1113
  type = undefined;
1107
1114
  }
1108
1115
 
1109
- const merge = options?.merge;
1110
- const adhoc = type && type !== true;
1116
+ // `type === true` means this document is being constructed. Otherwise,
1117
+ // `type` is an optional type for an "on-the-fly" path.
1111
1118
  const constructing = type === true;
1112
- let adhocs;
1113
- let keys;
1114
- let i = 0;
1115
- let pathtype;
1116
- let key;
1117
- let prefix;
1118
-
1119
- const userSpecifiedStrict = options && 'strict' in options;
1120
- let strict = userSpecifiedStrict
1121
- ? options.strict
1122
- : this.$__.strictMode;
1123
-
1124
- if (adhoc) {
1125
- adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
1119
+ if (type && !constructing) {
1120
+ const adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
1126
1121
  adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options);
1127
1122
  }
1128
1123
 
1124
+ const userSpecifiedStrict = options != null && 'strict' in options;
1125
+ let strict = userSpecifiedStrict ? options.strict : this.$__.strictMode;
1126
+
1127
+ // Support legacy `doc.set(null, path)` syntax, which sets `path` to `null`
1129
1128
  if (path == null) {
1130
1129
  [path, val] = [val, path];
1131
- } else if (typeof path !== 'string') {
1132
- // new Document({ key: val })
1133
- if (path instanceof Document) {
1134
- if (path.$__isNested) {
1135
- path = path.toObject();
1130
+ }
1131
+
1132
+ if (typeof path !== 'string') {
1133
+ // `doc.set(obj)`, or `doc.set(obj, prefix)` to set paths underneath `prefix`
1134
+ let obj = path;
1135
+ if (obj instanceof Document) {
1136
+ if (obj.$__isNested) {
1137
+ obj = obj.toObject();
1136
1138
  } else {
1137
1139
  // This ternary is to support gh-7898 (copying virtuals if same schema)
1138
1140
  // while not breaking gh-10819, which for some reason breaks if we use toObject()
1139
- path = path.$__schema === this.$__schema
1140
- ? applyVirtuals(path, { ...path._doc })
1141
- : path._doc;
1141
+ obj = obj.$__schema === this.$__schema
1142
+ ? applyVirtuals(obj, { ...obj._doc })
1143
+ : obj._doc;
1142
1144
  }
1143
1145
  }
1144
- if (path == null) {
1145
- [path, val] = [val, path];
1146
- }
1147
-
1148
- prefix = val ? val + '.' : '';
1149
- keys = getKeysInSchemaOrder(this.$__schema, path);
1150
1146
 
1151
- const len = keys.length;
1152
-
1153
- // `_skipMinimizeTopLevel` is because we may have deleted the top-level
1154
- // nested key to ensure key order.
1155
- const _skipMinimizeTopLevel = options?._skipMinimizeTopLevel || false;
1156
- if (len === 0 && _skipMinimizeTopLevel) {
1157
- delete options._skipMinimizeTopLevel;
1158
- if (val) {
1159
- this.$set(val, {});
1160
- }
1161
- return this;
1162
- }
1163
-
1164
- // Only need to clone if we're overwriting `_skipMinimizeTopLevel`, recursive
1165
- // calls treat a missing `_skipMinimizeTopLevel` as `false`
1166
- if (_skipMinimizeTopLevel) {
1167
- options = Object.assign({}, options, { _skipMinimizeTopLevel: false });
1168
- }
1169
-
1170
- for (let i = 0; i < len; ++i) {
1171
- key = keys[i];
1172
- const pathName = prefix ? prefix + key : key;
1173
- pathtype = this.$__schema.pathType(pathName);
1174
- const valForKey = path[key];
1147
+ const prefix = val ? val + '.' : '';
1148
+ for (const key of getKeysInSchemaOrder(this.$__schema, obj)) {
1149
+ const fullPath = prefix + key;
1150
+ const value = obj[key];
1151
+ let pathType = this.$__schema.pathType(fullPath);
1175
1152
 
1176
1153
  // On initial set, delete any nested keys if we're going to overwrite
1177
1154
  // them to ensure we keep the user's key order.
1178
- if (type === true &&
1179
- !prefix &&
1180
- valForKey != null &&
1181
- pathtype === 'nested' &&
1182
- this._doc[key] != null) {
1155
+ if (constructing && !prefix && value != null && pathType === 'nested' && this._doc[key] != null) {
1183
1156
  delete this._doc[key];
1184
1157
  }
1185
1158
 
1186
- if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') {
1187
- this.$set(pathName, valForKey, constructing, options);
1188
- $applyDefaultsToNested(this.$get(pathName), pathName, this);
1159
+ if (pathType === 'nested' && utils.isNonBuiltinObject(value)) {
1160
+ this.$set(fullPath, value, constructing, options);
1161
+ $applyDefaultsToNested(this.$get(fullPath), fullPath, this);
1189
1162
  continue;
1190
- } else if (strict) {
1163
+ }
1164
+ if (strict) {
1191
1165
  // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)
1192
- if (constructing && valForKey === void 0 &&
1193
- this.$get(pathName) !== void 0) {
1166
+ if (constructing && value === void 0 && this.$get(fullPath) !== void 0) {
1194
1167
  continue;
1195
1168
  }
1196
-
1197
- if (pathtype === 'adhocOrUndefined') {
1198
- pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
1169
+ if (pathType === 'adhocOrUndefined') {
1170
+ pathType = getEmbeddedDiscriminatorPath(this, fullPath, { typeOnly: true });
1199
1171
  }
1200
-
1201
- if (pathtype === 'real' || pathtype === 'virtual') {
1202
- this.$set(pathName, valForKey, constructing, options);
1203
- } else if (pathtype === 'nested' && valForKey instanceof Document) {
1204
- this.$set(pathName,
1205
- valForKey.toObject({ transform: false }), constructing, options);
1206
- } else if (strict === 'throw') {
1207
- if (pathtype === 'nested') {
1208
- throw new ObjectExpectedError(key, valForKey);
1209
- } else {
1210
- throw new StrictModeError(key);
1172
+ if (pathType !== 'real' && pathType !== 'virtual') {
1173
+ if (strict === 'throw') {
1174
+ throw pathType === 'nested' ? new ObjectExpectedError(key, value) : new StrictModeError(key);
1175
+ }
1176
+ // Strict mode only allows setting a nested path to null or undefined
1177
+ if (pathType !== 'nested' || value != null) {
1178
+ continue;
1211
1179
  }
1212
- } else if (pathtype === 'nested' && valForKey == null) {
1213
- this.$set(pathName, valForKey, constructing, options);
1214
1180
  }
1215
- } else {
1216
- this.$set(pathName, valForKey, constructing, options);
1217
1181
  }
1182
+ this.$set(fullPath, value, constructing, options);
1218
1183
  }
1219
1184
 
1220
- // Ensure all properties are in correct order
1185
+ // Ensure all properties are in schema order
1221
1186
  const orderedDoc = {};
1222
- const orderedKeys = Object.keys(this.$__schema.tree);
1223
- for (let i = 0, len = orderedKeys.length; i < len; ++i) {
1224
- (key = orderedKeys[i]) &&
1225
- (Object.hasOwn(this._doc, key)) &&
1226
- (orderedDoc[key] = undefined);
1187
+ for (const key of Object.keys(this.$__schema.tree)) {
1188
+ if (Object.hasOwn(this._doc, key)) {
1189
+ orderedDoc[key] = undefined;
1190
+ }
1227
1191
  }
1228
1192
  this._doc = Object.assign(orderedDoc, this._doc);
1229
1193
 
1230
1194
  return this;
1231
1195
  }
1232
1196
 
1197
+ // Setting a path underneath a top-level alias, like `alias.child`, is the
1198
+ // same as setting the path underneath the aliased path (gh-7592)
1199
+ const firstDot = path.indexOf('.');
1200
+ if (firstDot !== -1) {
1201
+ const alias = this.$__schema.aliases[path.slice(0, firstDot)];
1202
+ if (typeof alias === 'string') {
1203
+ path = alias + path.slice(firstDot);
1204
+ }
1205
+ }
1206
+
1207
+ // Resolving an alias keeps the `.child` suffix, so `path` still contains a '.'
1208
+ const parts = firstDot === -1 ? [path] : path.split('.');
1233
1209
  let pathType = this.$__schema.pathType(path);
1234
- let parts = null;
1235
1210
  if (pathType === 'adhocOrUndefined') {
1236
- parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1237
1211
  pathType = getEmbeddedDiscriminatorPath(this, parts, { typeOnly: true });
1238
1212
  }
1239
1213
  if (pathType === 'adhocOrUndefined' && !userSpecifiedStrict) {
1240
1214
  // May be path underneath non-strict schema
1241
- if (parts == null) {
1242
- parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1243
- }
1244
1215
  const subdocStrict = getSubdocumentStrictValue(this.$__schema, parts);
1245
1216
  if (subdocStrict !== undefined) {
1246
1217
  strict = subdocStrict;
@@ -1257,149 +1228,95 @@ Document.prototype.$set = function $set(path, val, type, options) {
1257
1228
  (constructing ? void 0 : this.$__getValue(path));
1258
1229
 
1259
1230
  if (pathType === 'nested' && val) {
1260
- if (typeof val === 'object' && val != null) {
1231
+ if (typeof val === 'object') {
1261
1232
  val = toObjectRecursive(val, internalToObjectOptions);
1262
- if (val == null) {
1263
- this.invalidate(path, new MongooseError.CastError('Object', val, path));
1264
- return this;
1265
- }
1266
- const wasModified = this.$isModified(path);
1267
- const hasInitialVal = this.$__.savedState != null && Object.hasOwn(this.$__.savedState, path);
1268
- if (this.$__.savedState != null && !this.$isNew && !Object.hasOwn(this.$__.savedState, path)) {
1269
- const initialVal = this.$__getValue(path);
1270
- this.$__.savedState[path] = initialVal;
1271
-
1272
- const keys = Object.keys(initialVal || {});
1273
- for (const key of keys) {
1274
- this.$__.savedState[path + '.' + key] = initialVal[key];
1275
- }
1276
- }
1233
+ }
1234
+ if (val == null || typeof val !== 'object') {
1235
+ this.invalidate(path, new MongooseError.CastError('Object', val, path));
1236
+ return this;
1237
+ }
1277
1238
 
1278
- if (!merge) {
1279
- this.$__setValue(path, null);
1280
- cleanModifiedSubpaths(this, path);
1281
- } else {
1282
- return this.$set(val, path, constructing, options);
1239
+ const savedState = this.$__.savedState;
1240
+ const hasInitialVal = savedState != null && Object.hasOwn(savedState, path);
1241
+ if (savedState != null && !this.$isNew && !hasInitialVal) {
1242
+ const initialVal = this.$__getValue(path);
1243
+ savedState[path] = initialVal;
1244
+ for (const key of Object.keys(initialVal || {})) {
1245
+ savedState[path + '.' + key] = initialVal[key];
1283
1246
  }
1247
+ }
1284
1248
 
1285
- const keys = getKeysInSchemaOrder(this.$__schema, val, path);
1249
+ if (options?.merge) {
1250
+ return this.$set(val, path, constructing, options);
1251
+ }
1286
1252
 
1287
- this.$__setValue(path, {});
1288
- for (const key of keys) {
1289
- this.$set(path + '.' + key, val[key], constructing, { ...options, _skipMarkModified: true });
1290
- }
1291
- if (priorVal != null &&
1292
- (!wasModified || hasInitialVal) &&
1293
- utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) {
1294
- this.unmarkModified(path);
1295
- } else {
1296
- this.markModified(path);
1297
- }
1298
- return this;
1253
+ // Overwrite the nested path's existing value, and only mark the nested
1254
+ // path modified if the new value is different.
1255
+ const wasModified = this.$isModified(path);
1256
+ cleanModifiedSubpaths(this, path);
1257
+ this.$__setValue(path, {});
1258
+ const setOptions = { ...options, _skipMarkModified: true };
1259
+ for (const key of getKeysInSchemaOrder(this.$__schema, val, path)) {
1260
+ this.$set(path + '.' + key, val[key], constructing, setOptions);
1261
+ }
1262
+ if (priorVal != null &&
1263
+ (!wasModified || hasInitialVal) &&
1264
+ utils.deepEqual(hasInitialVal ? savedState[path] : priorVal, val)) {
1265
+ this.unmarkModified(path);
1266
+ } else {
1267
+ this.markModified(path);
1299
1268
  }
1300
- this.invalidate(path, new MongooseError.CastError('Object', val, path));
1301
1269
  return this;
1302
1270
  }
1303
1271
 
1304
1272
  let schema;
1305
- if (parts == null) {
1306
- parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1307
- }
1308
-
1309
- // Might need to change path for top-level alias
1310
- if (typeof this.$__schema.aliases[parts[0]] === 'string') {
1311
- parts[0] = this.$__schema.aliases[parts[0]];
1312
- }
1313
-
1314
1273
  if (pathType === 'adhocOrUndefined' && strict) {
1315
- // check for roots that are Mixed types
1316
- let mixed;
1317
-
1318
- for (i = 0; i < parts.length; ++i) {
1319
- const subpath = parts.slice(0, i + 1).join('.');
1320
-
1321
- // If path is underneath a virtual, bypass everything and just set it.
1322
- if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') {
1274
+ // If path is underneath a virtual, bypass everything and just set it.
1275
+ let subpath = '';
1276
+ for (let i = 0; i < parts.length - 1; ++i) {
1277
+ subpath = i === 0 ? parts[0] : subpath + '.' + parts[i];
1278
+ if (this.$__schema.pathType(subpath) === 'virtual') {
1323
1279
  mpath.set(path, val, this);
1324
1280
  return this;
1325
1281
  }
1326
-
1327
- schema = this.$__schema.path(subpath);
1328
- if (schema == null) {
1329
- continue;
1330
- }
1331
-
1332
- if (schema instanceof MixedSchema) {
1333
- // allow changes to sub paths of mixed types
1334
- mixed = true;
1335
- break;
1336
- } else if (schema.$isSchemaMap && schema.$__schemaType instanceof MixedSchema && i < parts.length - 1) {
1337
- // Map of mixed and not the last element in the path resolves to mixed
1338
- mixed = true;
1339
- schema = schema.$__schemaType;
1340
- break;
1341
- }
1342
1282
  }
1343
1283
 
1284
+ // Check for embedded discriminators
1285
+ schema = this.$__schema.path(path) ?? getEmbeddedDiscriminatorPath(this, path);
1344
1286
  if (schema == null) {
1345
- // Check for embedded discriminators
1346
- schema = getEmbeddedDiscriminatorPath(this, path);
1347
- }
1348
-
1349
- if (!mixed && !schema) {
1350
1287
  if (strict === 'throw') {
1351
1288
  throw new StrictModeError(path);
1352
1289
  }
1353
1290
  return this;
1354
1291
  }
1355
1292
  } else if (pathType === 'virtual') {
1356
- schema = this.$__schema.virtualpath(path);
1357
- schema.applySetters(val, this);
1293
+ this.$__schema.virtualpath(path).applySetters(val, this);
1358
1294
  return this;
1359
1295
  } else {
1360
1296
  schema = this.$__path(path);
1361
1297
  }
1362
1298
 
1363
- // gh-4578, if setting a deeply nested path that doesn't exist yet, create it
1299
+ // gh-4578, if setting a deeply nested path that doesn't exist yet, create it.
1300
+ // MongoDB can't `$set` a path underneath a null value, so if creating the
1301
+ // path didn't replace a null value, mark the null ancestor modified instead.
1302
+ let pathToMark = path;
1364
1303
  let cur = this._doc;
1365
1304
  let curPath = '';
1366
- for (i = 0; i < parts.length - 1; ++i) {
1305
+ for (let i = 0; i < parts.length - 1; ++i) {
1367
1306
  cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]];
1368
1307
  curPath += (curPath.length !== 0 ? '.' : '') + parts[i];
1369
1308
  if (!cur) {
1370
1309
  this.$set(curPath, {});
1371
- // Hack re: gh-5800. If nested field is not selected, it probably exists
1372
- // so `MongoServerError: cannot use the part (nested of nested.num) to
1373
- // traverse the element ({nested: null})` is not likely. If user gets
1374
- // that error, its their fault for now. We should reconsider disallowing
1375
- // modifying not selected paths for 6.x
1310
+ // If nested field is not selected, avoid overwriting it. Re: gh-5800.
1376
1311
  if (!this.$__isSelected(curPath)) {
1377
1312
  this.unmarkModified(curPath);
1378
1313
  }
1379
1314
  cur = this.$__getValue(curPath);
1380
- }
1381
- }
1382
-
1383
- let pathToMark;
1384
-
1385
- // When using the $set operator the path to the field must already exist.
1386
- // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
1387
-
1388
- if (parts.length <= 1) {
1389
- pathToMark = path;
1390
- } else {
1391
- const len = parts.length;
1392
- for (i = 0; i < len; ++i) {
1393
- const subpath = parts.slice(0, i + 1).join('.');
1394
- if (this.$get(subpath, null, { getters: false }) === null) {
1395
- pathToMark = subpath;
1315
+ if (cur === null) {
1316
+ pathToMark = curPath;
1396
1317
  break;
1397
1318
  }
1398
1319
  }
1399
-
1400
- if (!pathToMark) {
1401
- pathToMark = path;
1402
- }
1403
1320
  }
1404
1321
 
1405
1322
  if (!schema) {
@@ -1418,15 +1335,13 @@ Document.prototype.$set = function $set(path, val, type, options) {
1418
1335
  _markValidSubpaths(this, path);
1419
1336
  }
1420
1337
 
1421
- if (val != null && merge && schema.$isSingleNested) {
1338
+ if (val != null && options?.merge && schema.$isSingleNested) {
1422
1339
  if (val instanceof Document) {
1423
1340
  val = val.toObject({ virtuals: false, transform: false });
1424
1341
  }
1425
- const keys = Object.keys(val);
1426
- for (const key of keys) {
1342
+ for (const key of Object.keys(val)) {
1427
1343
  this.$set(path + '.' + key, val[key], constructing, options);
1428
1344
  }
1429
-
1430
1345
  return this;
1431
1346
  }
1432
1347
 
@@ -1434,69 +1349,51 @@ Document.prototype.$set = function $set(path, val, type, options) {
1434
1349
  try {
1435
1350
  // If the user is trying to set a ref path to a document with
1436
1351
  // the correct model name, treat it as populated
1437
- const refMatches = !(val instanceof Document) ? false : (() => {
1438
- if (schema.options == null) {
1439
- return false;
1440
- }
1441
- const model = val.constructor;
1442
-
1443
- // Check ref
1444
- const refOpt = typeof schema.options.ref === 'function' && !schema.options.ref[modelSymbol] ? schema.options.ref.call(this, this) : schema.options.ref;
1445
-
1446
- const ref = refOpt?.modelName || refOpt;
1447
- if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
1448
- return true;
1449
- }
1450
-
1451
- // Check refPath
1452
- let refPath = schema.options.refPath;
1453
- if (refPath == null) {
1454
- return false;
1455
- }
1456
-
1457
- if (typeof refPath === 'function' && !refPath[modelSymbol]) {
1458
- let fullPath = path;
1459
- const fullPathWithIndexes = this.$__fullPathWithIndexes?.();
1460
- if (fullPathWithIndexes?.length) {
1461
- fullPath = fullPathWithIndexes + '.' + path;
1352
+ let refMatches = false;
1353
+ if (val instanceof Document && schema.options != null) {
1354
+ const { modelName, baseModelName } = val.constructor;
1355
+ let ref = schema.options.ref;
1356
+ if (typeof ref === 'function' && !ref[modelSymbol]) {
1357
+ ref = ref.call(this, this);
1358
+ }
1359
+ ref = ref?.modelName || ref;
1360
+
1361
+ if (ref != null && (ref === modelName || ref === baseModelName)) {
1362
+ refMatches = true;
1363
+ } else if (schema.options.refPath != null) {
1364
+ let refPath = schema.options.refPath;
1365
+ if (typeof refPath === 'function' && !refPath[modelSymbol]) {
1366
+ const fullPathWithIndexes = this.$__fullPathWithIndexes?.();
1367
+ refPath = refPath.call(this, this, fullPathWithIndexes ? fullPathWithIndexes + '.' + path : path);
1462
1368
  }
1463
- refPath = refPath.call(this, this, fullPath);
1464
- }
1465
-
1466
- if (typeof refPath !== 'string') {
1467
- throw new MongooseError('`refPath` must be a string or a function that returns a string, got ' + inspect(refPath));
1369
+ if (typeof refPath !== 'string') {
1370
+ throw new MongooseError('`refPath` must be a string or a function that returns a string, got ' + inspect(refPath));
1371
+ }
1372
+ const refModelName = this.ownerDocument().get(refPath);
1373
+ refMatches = refModelName === modelName || refModelName === baseModelName;
1468
1374
  }
1469
-
1470
- const modelName = this.ownerDocument().get(refPath);
1471
- return modelName === model.modelName || modelName === model.baseModelName;
1472
- })();
1375
+ }
1473
1376
 
1474
1377
  let didPopulate = false;
1475
- if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._doc._id))) {
1476
- const unpopulatedValue = schema?.$isSingleNested ? schema.cast(val, this) : val._doc._id;
1378
+ if (refMatches && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._doc._id))) {
1379
+ const unpopulatedValue = schema.$isSingleNested ? schema.cast(val, this) : val._doc._id;
1477
1380
  this.$populated(path, unpopulatedValue, { [populateModelSymbol]: val.constructor });
1478
1381
  val.$__.wasPopulated = { value: unpopulatedValue };
1479
1382
  didPopulate = true;
1480
1383
  }
1481
1384
 
1482
- let popOpts;
1483
- const typeKey = this.$__schema.options.typeKey;
1484
- if (schema.options &&
1485
- Array.isArray(schema.options[typeKey]) &&
1486
- schema.options[typeKey].length &&
1487
- schema.options[typeKey][0] &&
1488
- schema.options[typeKey][0].ref &&
1489
- _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) {
1490
- popOpts = { [populateModelSymbol]: val[0].constructor };
1491
- this.$populated(path, val.map(function(v) { return v._doc._id; }), popOpts);
1492
-
1385
+ // Same for setting an array of refs to an array of documents
1386
+ const arrayType = schema.options?.[this.$__schema.options.typeKey];
1387
+ const arrayRef = Array.isArray(arrayType) ? arrayType[0]?.ref : null;
1388
+ if (arrayRef && _isManuallyPopulatedArray(val, arrayRef)) {
1389
+ this.$populated(path, val.map(v => v._doc._id), { [populateModelSymbol]: val[0].constructor });
1493
1390
  for (const doc of val) {
1494
1391
  doc.$__.wasPopulated = { value: doc._doc._id };
1495
1392
  }
1496
1393
  didPopulate = true;
1497
1394
  }
1498
1395
 
1499
- if (!refMatches || !schema.$isSingleNested || !val.$__) {
1396
+ if (!refMatches || !schema.$isSingleNested) {
1500
1397
  // If this path is underneath a single nested schema, we'll call the setter
1501
1398
  // later in `$__set()` because we don't take `_doc` when we iterate through
1502
1399
  // a single nested doc. That's to make sure we get the correct context.
@@ -1505,23 +1402,20 @@ Document.prototype.$set = function $set(path, val, type, options) {
1505
1402
  if (this.$__schema.singleNestedPaths[path] != null && parts.length > 1) {
1506
1403
  setterContext = getDeepestSubdocumentForPath(this, parts, this.schema);
1507
1404
  }
1405
+ const setterOptions = { path };
1508
1406
  if (options?.overwriteImmutable) {
1509
- val = schema.applySetters(val, setterContext, false, priorVal, { path, overwriteImmutable: true });
1510
- } else {
1511
- val = schema.applySetters(val, setterContext, false, priorVal, { path });
1407
+ setterOptions.overwriteImmutable = true;
1512
1408
  }
1409
+ val = schema.applySetters(val, setterContext, false, priorVal, setterOptions);
1513
1410
  }
1514
1411
 
1515
- if (Array.isArray(val) &&
1516
- !Array.isArray(schema) &&
1517
- schema.$isMongooseDocumentArray &&
1518
- val.length !== 0 &&
1519
- val[0]?.$__?.populated != null) {
1520
- const populatedPaths = Object.keys(val[0].$__.populated);
1521
- for (const populatedPath of populatedPaths) {
1412
+ // Track populated paths of documents in a document array
1413
+ if (schema.$isMongooseDocumentArray && Array.isArray(val) && val[0]?.$__?.populated != null) {
1414
+ const populated = val[0].$__.populated;
1415
+ for (const populatedPath of Object.keys(populated)) {
1522
1416
  this.$populated(path + '.' + populatedPath,
1523
1417
  val.map(v => v.$populated(populatedPath)),
1524
- val[0].$__.populated[populatedPath].options);
1418
+ populated[populatedPath].options);
1525
1419
  }
1526
1420
  didPopulate = true;
1527
1421
  }
@@ -1549,10 +1443,6 @@ Document.prototype.$set = function $set(path, val, type, options) {
1549
1443
  this.invalidate(path, e);
1550
1444
  } else if (e instanceof MongooseError.CastError) {
1551
1445
  this.invalidate(e.path, e);
1552
- if (e.$originalErrorPath) {
1553
- this.invalidate(path,
1554
- new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath));
1555
- }
1556
1446
  } else {
1557
1447
  this.invalidate(path,
1558
1448
  new MongooseError.CastError(schema.instance, val, path, e));
@@ -1572,23 +1462,22 @@ Document.prototype.$set = function $set(path, val, type, options) {
1572
1462
 
1573
1463
  this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal);
1574
1464
 
1575
- const isInTransaction = !!this.$__.session?.transaction;
1576
- const isModifiedWithinTransaction = this.$__.session &&
1577
- this.$__.session[sessionNewDocuments] &&
1578
- this.$__.session[sessionNewDocuments].has(this) &&
1579
- this.$__.session[sessionNewDocuments].get(this).modifiedPaths &&
1580
- !this.$__.session[sessionNewDocuments].get(this).modifiedPaths.has(savedStatePath);
1581
- if (savedState != null &&
1582
- Object.hasOwn(savedState, savedStatePath) &&
1583
- (!isInTransaction || isModifiedWithinTransaction) &&
1584
- utils.deepEqual(val, savedState[savedStatePath])) {
1585
- this.unmarkModified(path);
1465
+ // Setting a path back to its initial value means it isn't modified anymore,
1466
+ // unless it was already modified in the current transaction.
1467
+ if (savedState != null && Object.hasOwn(savedState, savedStatePath)) {
1468
+ const session = this.$__.session;
1469
+ const modifiedPathsInTransaction = session?.[sessionNewDocuments]?.get(this)?.modifiedPaths;
1470
+ const isModifiedWithinTransaction = modifiedPathsInTransaction != null &&
1471
+ !modifiedPathsInTransaction.has(savedStatePath);
1472
+ if ((!session?.transaction || isModifiedWithinTransaction) &&
1473
+ utils.deepEqual(val, savedState[savedStatePath])) {
1474
+ this.unmarkModified(path);
1475
+ }
1586
1476
  }
1587
1477
  }
1588
1478
 
1589
- if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
1590
- cleanModifiedSubpaths(this, path);
1591
- } else if (schema.$isSchemaMap && val == null) {
1479
+ if ((schema.$isSingleNested && (this.isDirectModified(path) || val == null)) ||
1480
+ (schema.$isSchemaMap && val == null)) {
1592
1481
  cleanModifiedSubpaths(this, path);
1593
1482
  }
1594
1483
 
@@ -1730,7 +1619,7 @@ Document.prototype.$__shouldModify = function(pathToMark, path, options, constru
1730
1619
  /**
1731
1620
  * Handles the actual setting of the value and marking the path modified if appropriate.
1732
1621
  *
1733
- * @param {string} pathToMark
1622
+ * @param {string} pathToMark the path to mark modified, either `path` or a null ancestor of `path`
1734
1623
  * @param {string|symbol} path
1735
1624
  * @param {object} options
1736
1625
  * @param {any} constructing
@@ -3902,10 +3791,12 @@ Document.prototype.$__reset = function reset(skipBackup, hasOnlyPrimitiveValues)
3902
3791
  }
3903
3792
 
3904
3793
  if (!skipBackup) {
3794
+ // No need to copy the state buckets: `clearAllExcept()` below replaces
3795
+ // them rather than modifying them, so the backup holds the only reference.
3905
3796
  this.$__.backup = {};
3906
3797
  this.$__.backup.activePaths = {
3907
- modify: Object.assign({}, this.$__.activePaths.getStatePaths('modify')),
3908
- default: Object.assign({}, this.$__.activePaths.getStatePaths('default'))
3798
+ modify: this.$__.activePaths.getStatePaths('modify'),
3799
+ default: this.$__.activePaths.getStatePaths('default')
3909
3800
  };
3910
3801
  this.$__.backup.validationError = this.$__.validationError;
3911
3802
  this.$__.backup.errors = this.$errors;
@@ -3947,8 +3838,16 @@ function _clearAtomicsOnPaths(doc, paths) {
3947
3838
  if (paths == null) {
3948
3839
  return;
3949
3840
  }
3841
+ const schemaPaths = doc.$__schema.paths;
3950
3842
  const keys = Object.keys(paths);
3951
3843
  for (let i = 0; i < keys.length; ++i) {
3844
+ // Arrays and maps have atomics, and unions and Mixed paths may hold arrays
3845
+ // or maps. Paths not in `schema.paths`, like `arr.0` or nested paths, may
3846
+ // contain them too.
3847
+ const schemaType = Object.hasOwn(schemaPaths, keys[i]) ? schemaPaths[keys[i]] : null;
3848
+ if (schemaType != null && !schemaType.$isMongooseArray && !schemaType.$isSchemaMap && !schemaType.$isSchemaUnion && schemaType.instance !== 'Mixed') {
3849
+ continue;
3850
+ }
3952
3851
  const type = doc.$__getValue(keys[i]);
3953
3852
  if (type != null) {
3954
3853
  if (typeof type.clearAtomics === 'function') {