mongoose 9.11.3 → 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) {
@@ -792,7 +797,11 @@ function init(self, obj, doc, opts, prefix) {
792
797
  }
793
798
 
794
799
  if (!schemaType && utils.isPOJO(value)) {
795
- // assume nested object
800
+ // assume nested object. Skip inherited properties like `Object.prototype.toString`
801
+ // to avoid setting properties on shared objects
802
+ if (!Object.hasOwn(doc, i) && i in doc) {
803
+ continue;
804
+ }
796
805
  if (!doc[i]) {
797
806
  doc[i] = {};
798
807
  if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
@@ -862,9 +871,11 @@ function init(self, obj, doc, opts, prefix) {
862
871
  doc[i] = value;
863
872
  }
864
873
  }
865
- // mark as hydrated
866
- if (!self.$isModified(path)) {
867
- 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);
868
879
  }
869
880
  }
870
881
  }
@@ -1102,141 +1113,105 @@ Document.prototype.$set = function $set(path, val, type, options) {
1102
1113
  type = undefined;
1103
1114
  }
1104
1115
 
1105
- const merge = options?.merge;
1106
- 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.
1107
1118
  const constructing = type === true;
1108
- let adhocs;
1109
- let keys;
1110
- let i = 0;
1111
- let pathtype;
1112
- let key;
1113
- let prefix;
1114
-
1115
- const userSpecifiedStrict = options && 'strict' in options;
1116
- let strict = userSpecifiedStrict
1117
- ? options.strict
1118
- : this.$__.strictMode;
1119
-
1120
- if (adhoc) {
1121
- adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
1119
+ if (type && !constructing) {
1120
+ const adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
1122
1121
  adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options);
1123
1122
  }
1124
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`
1125
1128
  if (path == null) {
1126
1129
  [path, val] = [val, path];
1127
- } else if (typeof path !== 'string') {
1128
- // new Document({ key: val })
1129
- if (path instanceof Document) {
1130
- if (path.$__isNested) {
1131
- 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();
1132
1138
  } else {
1133
1139
  // This ternary is to support gh-7898 (copying virtuals if same schema)
1134
1140
  // while not breaking gh-10819, which for some reason breaks if we use toObject()
1135
- path = path.$__schema === this.$__schema
1136
- ? applyVirtuals(path, { ...path._doc })
1137
- : path._doc;
1138
- }
1139
- }
1140
- if (path == null) {
1141
- [path, val] = [val, path];
1142
- }
1143
-
1144
- prefix = val ? val + '.' : '';
1145
- keys = getKeysInSchemaOrder(this.$__schema, path);
1146
-
1147
- const len = keys.length;
1148
-
1149
- // `_skipMinimizeTopLevel` is because we may have deleted the top-level
1150
- // nested key to ensure key order.
1151
- const _skipMinimizeTopLevel = options?._skipMinimizeTopLevel || false;
1152
- if (len === 0 && _skipMinimizeTopLevel) {
1153
- delete options._skipMinimizeTopLevel;
1154
- if (val) {
1155
- this.$set(val, {});
1141
+ obj = obj.$__schema === this.$__schema
1142
+ ? applyVirtuals(obj, { ...obj._doc })
1143
+ : obj._doc;
1156
1144
  }
1157
- return this;
1158
1145
  }
1159
1146
 
1160
- // Only need to clone if we're overwriting `_skipMinimizeTopLevel`, recursive
1161
- // calls treat a missing `_skipMinimizeTopLevel` as `false`
1162
- if (_skipMinimizeTopLevel) {
1163
- options = Object.assign({}, options, { _skipMinimizeTopLevel: false });
1164
- }
1165
-
1166
- for (let i = 0; i < len; ++i) {
1167
- key = keys[i];
1168
- const pathName = prefix ? prefix + key : key;
1169
- pathtype = this.$__schema.pathType(pathName);
1170
- 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);
1171
1152
 
1172
1153
  // On initial set, delete any nested keys if we're going to overwrite
1173
1154
  // them to ensure we keep the user's key order.
1174
- if (type === true &&
1175
- !prefix &&
1176
- valForKey != null &&
1177
- pathtype === 'nested' &&
1178
- this._doc[key] != null) {
1155
+ if (constructing && !prefix && value != null && pathType === 'nested' && this._doc[key] != null) {
1179
1156
  delete this._doc[key];
1180
1157
  }
1181
1158
 
1182
- if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') {
1183
- this.$set(pathName, valForKey, constructing, options);
1184
- $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);
1185
1162
  continue;
1186
- } else if (strict) {
1163
+ }
1164
+ if (strict) {
1187
1165
  // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)
1188
- if (constructing && valForKey === void 0 &&
1189
- this.$get(pathName) !== void 0) {
1166
+ if (constructing && value === void 0 && this.$get(fullPath) !== void 0) {
1190
1167
  continue;
1191
1168
  }
1192
-
1193
- if (pathtype === 'adhocOrUndefined') {
1194
- pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
1169
+ if (pathType === 'adhocOrUndefined') {
1170
+ pathType = getEmbeddedDiscriminatorPath(this, fullPath, { typeOnly: true });
1195
1171
  }
1196
-
1197
- if (pathtype === 'real' || pathtype === 'virtual') {
1198
- this.$set(pathName, valForKey, constructing, options);
1199
- } else if (pathtype === 'nested' && valForKey instanceof Document) {
1200
- this.$set(pathName,
1201
- valForKey.toObject({ transform: false }), constructing, options);
1202
- } else if (strict === 'throw') {
1203
- if (pathtype === 'nested') {
1204
- throw new ObjectExpectedError(key, valForKey);
1205
- } else {
1206
- 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;
1207
1179
  }
1208
- } else if (pathtype === 'nested' && valForKey == null) {
1209
- this.$set(pathName, valForKey, constructing, options);
1210
1180
  }
1211
- } else {
1212
- this.$set(pathName, valForKey, constructing, options);
1213
1181
  }
1182
+ this.$set(fullPath, value, constructing, options);
1214
1183
  }
1215
1184
 
1216
- // Ensure all properties are in correct order
1185
+ // Ensure all properties are in schema order
1217
1186
  const orderedDoc = {};
1218
- const orderedKeys = Object.keys(this.$__schema.tree);
1219
- for (let i = 0, len = orderedKeys.length; i < len; ++i) {
1220
- (key = orderedKeys[i]) &&
1221
- (Object.hasOwn(this._doc, key)) &&
1222
- (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
+ }
1223
1191
  }
1224
1192
  this._doc = Object.assign(orderedDoc, this._doc);
1225
1193
 
1226
1194
  return this;
1227
1195
  }
1228
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('.');
1229
1209
  let pathType = this.$__schema.pathType(path);
1230
- let parts = null;
1231
1210
  if (pathType === 'adhocOrUndefined') {
1232
- parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1233
1211
  pathType = getEmbeddedDiscriminatorPath(this, parts, { typeOnly: true });
1234
1212
  }
1235
1213
  if (pathType === 'adhocOrUndefined' && !userSpecifiedStrict) {
1236
1214
  // May be path underneath non-strict schema
1237
- if (parts == null) {
1238
- parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1239
- }
1240
1215
  const subdocStrict = getSubdocumentStrictValue(this.$__schema, parts);
1241
1216
  if (subdocStrict !== undefined) {
1242
1217
  strict = subdocStrict;
@@ -1253,149 +1228,95 @@ Document.prototype.$set = function $set(path, val, type, options) {
1253
1228
  (constructing ? void 0 : this.$__getValue(path));
1254
1229
 
1255
1230
  if (pathType === 'nested' && val) {
1256
- if (typeof val === 'object' && val != null) {
1231
+ if (typeof val === 'object') {
1257
1232
  val = toObjectRecursive(val, internalToObjectOptions);
1258
- if (val == null) {
1259
- this.invalidate(path, new MongooseError.CastError('Object', val, path));
1260
- return this;
1261
- }
1262
- const wasModified = this.$isModified(path);
1263
- const hasInitialVal = this.$__.savedState != null && Object.hasOwn(this.$__.savedState, path);
1264
- if (this.$__.savedState != null && !this.$isNew && !Object.hasOwn(this.$__.savedState, path)) {
1265
- const initialVal = this.$__getValue(path);
1266
- this.$__.savedState[path] = initialVal;
1267
-
1268
- const keys = Object.keys(initialVal || {});
1269
- for (const key of keys) {
1270
- this.$__.savedState[path + '.' + key] = initialVal[key];
1271
- }
1272
- }
1233
+ }
1234
+ if (val == null || typeof val !== 'object') {
1235
+ this.invalidate(path, new MongooseError.CastError('Object', val, path));
1236
+ return this;
1237
+ }
1273
1238
 
1274
- if (!merge) {
1275
- this.$__setValue(path, null);
1276
- cleanModifiedSubpaths(this, path);
1277
- } else {
1278
- 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];
1279
1246
  }
1247
+ }
1280
1248
 
1281
- const keys = getKeysInSchemaOrder(this.$__schema, val, path);
1249
+ if (options?.merge) {
1250
+ return this.$set(val, path, constructing, options);
1251
+ }
1282
1252
 
1283
- this.$__setValue(path, {});
1284
- for (const key of keys) {
1285
- this.$set(path + '.' + key, val[key], constructing, { ...options, _skipMarkModified: true });
1286
- }
1287
- if (priorVal != null &&
1288
- (!wasModified || hasInitialVal) &&
1289
- utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) {
1290
- this.unmarkModified(path);
1291
- } else {
1292
- this.markModified(path);
1293
- }
1294
- 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);
1295
1268
  }
1296
- this.invalidate(path, new MongooseError.CastError('Object', val, path));
1297
1269
  return this;
1298
1270
  }
1299
1271
 
1300
1272
  let schema;
1301
- if (parts == null) {
1302
- parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1303
- }
1304
-
1305
- // Might need to change path for top-level alias
1306
- if (typeof this.$__schema.aliases[parts[0]] === 'string') {
1307
- parts[0] = this.$__schema.aliases[parts[0]];
1308
- }
1309
-
1310
1273
  if (pathType === 'adhocOrUndefined' && strict) {
1311
- // check for roots that are Mixed types
1312
- let mixed;
1313
-
1314
- for (i = 0; i < parts.length; ++i) {
1315
- const subpath = parts.slice(0, i + 1).join('.');
1316
-
1317
- // If path is underneath a virtual, bypass everything and just set it.
1318
- 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') {
1319
1279
  mpath.set(path, val, this);
1320
1280
  return this;
1321
1281
  }
1322
-
1323
- schema = this.$__schema.path(subpath);
1324
- if (schema == null) {
1325
- continue;
1326
- }
1327
-
1328
- if (schema instanceof MixedSchema) {
1329
- // allow changes to sub paths of mixed types
1330
- mixed = true;
1331
- break;
1332
- } else if (schema.$isSchemaMap && schema.$__schemaType instanceof MixedSchema && i < parts.length - 1) {
1333
- // Map of mixed and not the last element in the path resolves to mixed
1334
- mixed = true;
1335
- schema = schema.$__schemaType;
1336
- break;
1337
- }
1338
1282
  }
1339
1283
 
1284
+ // Check for embedded discriminators
1285
+ schema = this.$__schema.path(path) ?? getEmbeddedDiscriminatorPath(this, path);
1340
1286
  if (schema == null) {
1341
- // Check for embedded discriminators
1342
- schema = getEmbeddedDiscriminatorPath(this, path);
1343
- }
1344
-
1345
- if (!mixed && !schema) {
1346
1287
  if (strict === 'throw') {
1347
1288
  throw new StrictModeError(path);
1348
1289
  }
1349
1290
  return this;
1350
1291
  }
1351
1292
  } else if (pathType === 'virtual') {
1352
- schema = this.$__schema.virtualpath(path);
1353
- schema.applySetters(val, this);
1293
+ this.$__schema.virtualpath(path).applySetters(val, this);
1354
1294
  return this;
1355
1295
  } else {
1356
1296
  schema = this.$__path(path);
1357
1297
  }
1358
1298
 
1359
- // 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;
1360
1303
  let cur = this._doc;
1361
1304
  let curPath = '';
1362
- for (i = 0; i < parts.length - 1; ++i) {
1305
+ for (let i = 0; i < parts.length - 1; ++i) {
1363
1306
  cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]];
1364
1307
  curPath += (curPath.length !== 0 ? '.' : '') + parts[i];
1365
1308
  if (!cur) {
1366
1309
  this.$set(curPath, {});
1367
- // Hack re: gh-5800. If nested field is not selected, it probably exists
1368
- // so `MongoServerError: cannot use the part (nested of nested.num) to
1369
- // traverse the element ({nested: null})` is not likely. If user gets
1370
- // that error, its their fault for now. We should reconsider disallowing
1371
- // modifying not selected paths for 6.x
1310
+ // If nested field is not selected, avoid overwriting it. Re: gh-5800.
1372
1311
  if (!this.$__isSelected(curPath)) {
1373
1312
  this.unmarkModified(curPath);
1374
1313
  }
1375
1314
  cur = this.$__getValue(curPath);
1376
- }
1377
- }
1378
-
1379
- let pathToMark;
1380
-
1381
- // When using the $set operator the path to the field must already exist.
1382
- // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
1383
-
1384
- if (parts.length <= 1) {
1385
- pathToMark = path;
1386
- } else {
1387
- const len = parts.length;
1388
- for (i = 0; i < len; ++i) {
1389
- const subpath = parts.slice(0, i + 1).join('.');
1390
- if (this.$get(subpath, null, { getters: false }) === null) {
1391
- pathToMark = subpath;
1315
+ if (cur === null) {
1316
+ pathToMark = curPath;
1392
1317
  break;
1393
1318
  }
1394
1319
  }
1395
-
1396
- if (!pathToMark) {
1397
- pathToMark = path;
1398
- }
1399
1320
  }
1400
1321
 
1401
1322
  if (!schema) {
@@ -1414,15 +1335,13 @@ Document.prototype.$set = function $set(path, val, type, options) {
1414
1335
  _markValidSubpaths(this, path);
1415
1336
  }
1416
1337
 
1417
- if (val != null && merge && schema.$isSingleNested) {
1338
+ if (val != null && options?.merge && schema.$isSingleNested) {
1418
1339
  if (val instanceof Document) {
1419
1340
  val = val.toObject({ virtuals: false, transform: false });
1420
1341
  }
1421
- const keys = Object.keys(val);
1422
- for (const key of keys) {
1342
+ for (const key of Object.keys(val)) {
1423
1343
  this.$set(path + '.' + key, val[key], constructing, options);
1424
1344
  }
1425
-
1426
1345
  return this;
1427
1346
  }
1428
1347
 
@@ -1430,69 +1349,51 @@ Document.prototype.$set = function $set(path, val, type, options) {
1430
1349
  try {
1431
1350
  // If the user is trying to set a ref path to a document with
1432
1351
  // the correct model name, treat it as populated
1433
- const refMatches = !(val instanceof Document) ? false : (() => {
1434
- if (schema.options == null) {
1435
- return false;
1436
- }
1437
- const model = val.constructor;
1438
-
1439
- // Check ref
1440
- const refOpt = typeof schema.options.ref === 'function' && !schema.options.ref[modelSymbol] ? schema.options.ref.call(this, this) : schema.options.ref;
1441
-
1442
- const ref = refOpt?.modelName || refOpt;
1443
- if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
1444
- return true;
1445
- }
1446
-
1447
- // Check refPath
1448
- let refPath = schema.options.refPath;
1449
- if (refPath == null) {
1450
- return false;
1451
- }
1452
-
1453
- if (typeof refPath === 'function' && !refPath[modelSymbol]) {
1454
- let fullPath = path;
1455
- const fullPathWithIndexes = this.$__fullPathWithIndexes?.();
1456
- if (fullPathWithIndexes?.length) {
1457
- 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);
1458
1368
  }
1459
- refPath = refPath.call(this, this, fullPath);
1460
- }
1461
-
1462
- if (typeof refPath !== 'string') {
1463
- 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;
1464
1374
  }
1465
-
1466
- const modelName = this.ownerDocument().get(refPath);
1467
- return modelName === model.modelName || modelName === model.baseModelName;
1468
- })();
1375
+ }
1469
1376
 
1470
1377
  let didPopulate = false;
1471
- if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._doc._id))) {
1472
- 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;
1473
1380
  this.$populated(path, unpopulatedValue, { [populateModelSymbol]: val.constructor });
1474
1381
  val.$__.wasPopulated = { value: unpopulatedValue };
1475
1382
  didPopulate = true;
1476
1383
  }
1477
1384
 
1478
- let popOpts;
1479
- const typeKey = this.$__schema.options.typeKey;
1480
- if (schema.options &&
1481
- Array.isArray(schema.options[typeKey]) &&
1482
- schema.options[typeKey].length &&
1483
- schema.options[typeKey][0] &&
1484
- schema.options[typeKey][0].ref &&
1485
- _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) {
1486
- popOpts = { [populateModelSymbol]: val[0].constructor };
1487
- this.$populated(path, val.map(function(v) { return v._doc._id; }), popOpts);
1488
-
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 });
1489
1390
  for (const doc of val) {
1490
1391
  doc.$__.wasPopulated = { value: doc._doc._id };
1491
1392
  }
1492
1393
  didPopulate = true;
1493
1394
  }
1494
1395
 
1495
- if (!refMatches || !schema.$isSingleNested || !val.$__) {
1396
+ if (!refMatches || !schema.$isSingleNested) {
1496
1397
  // If this path is underneath a single nested schema, we'll call the setter
1497
1398
  // later in `$__set()` because we don't take `_doc` when we iterate through
1498
1399
  // a single nested doc. That's to make sure we get the correct context.
@@ -1501,23 +1402,20 @@ Document.prototype.$set = function $set(path, val, type, options) {
1501
1402
  if (this.$__schema.singleNestedPaths[path] != null && parts.length > 1) {
1502
1403
  setterContext = getDeepestSubdocumentForPath(this, parts, this.schema);
1503
1404
  }
1405
+ const setterOptions = { path };
1504
1406
  if (options?.overwriteImmutable) {
1505
- val = schema.applySetters(val, setterContext, false, priorVal, { path, overwriteImmutable: true });
1506
- } else {
1507
- val = schema.applySetters(val, setterContext, false, priorVal, { path });
1407
+ setterOptions.overwriteImmutable = true;
1508
1408
  }
1409
+ val = schema.applySetters(val, setterContext, false, priorVal, setterOptions);
1509
1410
  }
1510
1411
 
1511
- if (Array.isArray(val) &&
1512
- !Array.isArray(schema) &&
1513
- schema.$isMongooseDocumentArray &&
1514
- val.length !== 0 &&
1515
- val[0]?.$__?.populated != null) {
1516
- const populatedPaths = Object.keys(val[0].$__.populated);
1517
- 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)) {
1518
1416
  this.$populated(path + '.' + populatedPath,
1519
1417
  val.map(v => v.$populated(populatedPath)),
1520
- val[0].$__.populated[populatedPath].options);
1418
+ populated[populatedPath].options);
1521
1419
  }
1522
1420
  didPopulate = true;
1523
1421
  }
@@ -1545,10 +1443,6 @@ Document.prototype.$set = function $set(path, val, type, options) {
1545
1443
  this.invalidate(path, e);
1546
1444
  } else if (e instanceof MongooseError.CastError) {
1547
1445
  this.invalidate(e.path, e);
1548
- if (e.$originalErrorPath) {
1549
- this.invalidate(path,
1550
- new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath));
1551
- }
1552
1446
  } else {
1553
1447
  this.invalidate(path,
1554
1448
  new MongooseError.CastError(schema.instance, val, path, e));
@@ -1568,23 +1462,22 @@ Document.prototype.$set = function $set(path, val, type, options) {
1568
1462
 
1569
1463
  this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal);
1570
1464
 
1571
- const isInTransaction = !!this.$__.session?.transaction;
1572
- const isModifiedWithinTransaction = this.$__.session &&
1573
- this.$__.session[sessionNewDocuments] &&
1574
- this.$__.session[sessionNewDocuments].has(this) &&
1575
- this.$__.session[sessionNewDocuments].get(this).modifiedPaths &&
1576
- !this.$__.session[sessionNewDocuments].get(this).modifiedPaths.has(savedStatePath);
1577
- if (savedState != null &&
1578
- Object.hasOwn(savedState, savedStatePath) &&
1579
- (!isInTransaction || isModifiedWithinTransaction) &&
1580
- utils.deepEqual(val, savedState[savedStatePath])) {
1581
- 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
+ }
1582
1476
  }
1583
1477
  }
1584
1478
 
1585
- if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
1586
- cleanModifiedSubpaths(this, path);
1587
- } else if (schema.$isSchemaMap && val == null) {
1479
+ if ((schema.$isSingleNested && (this.isDirectModified(path) || val == null)) ||
1480
+ (schema.$isSchemaMap && val == null)) {
1588
1481
  cleanModifiedSubpaths(this, path);
1589
1482
  }
1590
1483
 
@@ -1726,7 +1619,7 @@ Document.prototype.$__shouldModify = function(pathToMark, path, options, constru
1726
1619
  /**
1727
1620
  * Handles the actual setting of the value and marking the path modified if appropriate.
1728
1621
  *
1729
- * @param {string} pathToMark
1622
+ * @param {string} pathToMark the path to mark modified, either `path` or a null ancestor of `path`
1730
1623
  * @param {string|symbol} path
1731
1624
  * @param {object} options
1732
1625
  * @param {any} constructing
@@ -1811,6 +1704,12 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
1811
1704
  } else {
1812
1705
  const isMap = obj instanceof Map;
1813
1706
  let value = isMap ? obj.get(parts[i]) : obj[parts[i]];
1707
+ // Skip inherited properties like `Object.prototype.toString`, document methods,
1708
+ // or document internals like `$__schema` to avoid setting properties on shared
1709
+ // objects. Document properties are getters on the prototype, so check `_doc`.
1710
+ if (!isMap && !Object.hasOwn(obj.$__ == null ? obj : obj._doc, parts[i]) && parts[i] in obj) {
1711
+ return;
1712
+ }
1814
1713
  if (utils.isPOJO(value)) {
1815
1714
  obj = value;
1816
1715
  } else if (value && value instanceof Embedded) {
@@ -3892,10 +3791,12 @@ Document.prototype.$__reset = function reset(skipBackup, hasOnlyPrimitiveValues)
3892
3791
  }
3893
3792
 
3894
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.
3895
3796
  this.$__.backup = {};
3896
3797
  this.$__.backup.activePaths = {
3897
- modify: Object.assign({}, this.$__.activePaths.getStatePaths('modify')),
3898
- default: Object.assign({}, this.$__.activePaths.getStatePaths('default'))
3798
+ modify: this.$__.activePaths.getStatePaths('modify'),
3799
+ default: this.$__.activePaths.getStatePaths('default')
3899
3800
  };
3900
3801
  this.$__.backup.validationError = this.$__.validationError;
3901
3802
  this.$__.backup.errors = this.$errors;
@@ -3937,8 +3838,16 @@ function _clearAtomicsOnPaths(doc, paths) {
3937
3838
  if (paths == null) {
3938
3839
  return;
3939
3840
  }
3841
+ const schemaPaths = doc.$__schema.paths;
3940
3842
  const keys = Object.keys(paths);
3941
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
+ }
3942
3851
  const type = doc.$__getValue(keys[i]);
3943
3852
  if (type != null) {
3944
3853
  if (typeof type.clearAtomics === 'function') {