mongoose 8.10.0 → 8.10.1

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/connection.js CHANGED
@@ -818,32 +818,41 @@ Connection.prototype.dropCollection = async function dropCollection(collection)
818
818
  /**
819
819
  * Waits for connection to be established, so the connection has a `client`
820
820
  *
821
+ * @param {Boolean} [noTimeout=false] if set, don't put a timeout on the operation. Used internally so `mongoose.model()` doesn't leave open handles.
821
822
  * @return Promise
822
823
  * @api private
823
824
  */
824
825
 
825
- Connection.prototype._waitForConnect = async function _waitForConnect() {
826
+ Connection.prototype._waitForConnect = async function _waitForConnect(noTimeout) {
826
827
  if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
827
828
  const bufferTimeoutMS = this._getBufferTimeoutMS();
828
829
  let timeout = null;
829
830
  let timedOut = false;
830
831
  // The element that this function pushes onto `_queue`, stored to make it easy to remove later
831
832
  const queueElement = {};
832
- await Promise.race([
833
- new Promise(resolve => {
834
- queueElement.fn = resolve;
835
- this._queue.push(queueElement);
836
- }),
837
- new Promise(resolve => {
838
- timeout = setTimeout(
839
- () => {
840
- timedOut = true;
841
- resolve();
842
- },
843
- bufferTimeoutMS
844
- );
845
- })
846
- ]);
833
+
834
+ // Mongoose executes all elements in `_queue` when initial connection succeeds in `onOpen()`.
835
+ const waitForConnectPromise = new Promise(resolve => {
836
+ queueElement.fn = resolve;
837
+ this._queue.push(queueElement);
838
+ });
839
+
840
+ if (noTimeout) {
841
+ await waitForConnectPromise;
842
+ } else {
843
+ await Promise.race([
844
+ waitForConnectPromise,
845
+ new Promise(resolve => {
846
+ timeout = setTimeout(
847
+ () => {
848
+ timedOut = true;
849
+ resolve();
850
+ },
851
+ bufferTimeoutMS
852
+ );
853
+ })
854
+ ]);
855
+ }
847
856
 
848
857
  if (timedOut) {
849
858
  const index = this._queue.indexOf(queueElement);
package/lib/document.js CHANGED
@@ -741,15 +741,10 @@ function init(self, obj, doc, opts, prefix) {
741
741
  let schemaType;
742
742
  let path;
743
743
  let i;
744
- let index = 0;
745
744
  const strict = self.$__.strictMode;
746
745
  const docSchema = self.$__schema;
747
746
 
748
- while (index < len) {
749
- _init(index++);
750
- }
751
-
752
- function _init(index) {
747
+ for (let index = 0; index < len; ++index) {
753
748
  i = keys[index];
754
749
  // avoid prototype pollution
755
750
  if (i === '__proto__' || i === 'constructor') {
@@ -3558,8 +3553,10 @@ Document.prototype.$__undoReset = function $__undoReset() {
3558
3553
  }
3559
3554
  }
3560
3555
 
3561
- for (const subdoc of this.$getAllSubdocs()) {
3562
- subdoc.$__undoReset();
3556
+ if (!this.$isSubdocument) {
3557
+ for (const subdoc of this.$getAllSubdocs()) {
3558
+ subdoc.$__undoReset();
3559
+ }
3563
3560
  }
3564
3561
  };
3565
3562
 
@@ -82,6 +82,16 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
82
82
  schema = schema.discriminators[discriminatorValue] ||
83
83
  (byValue && byValue.schema) ||
84
84
  schema;
85
+ } else if (schema != null &&
86
+ options.overwriteDiscriminatorKey &&
87
+ obj.$set != null &&
88
+ utils.hasUserDefinedProperty(obj.$set, schema.options.discriminatorKey) &&
89
+ schema.discriminators != null) {
90
+ const discriminatorValue = obj.$set[schema.options.discriminatorKey];
91
+ const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
92
+ schema = schema.discriminators[discriminatorValue] ||
93
+ (byValue && byValue.schema) ||
94
+ schema;
85
95
  }
86
96
 
87
97
  if (options.upsert) {
package/lib/model.js CHANGED
@@ -1103,16 +1103,28 @@ Model.init = function init() {
1103
1103
  return results;
1104
1104
  };
1105
1105
  const _createCollection = async() => {
1106
- await conn._waitForConnect();
1107
- const autoCreate = utils.getOption(
1106
+ let autoCreate = utils.getOption(
1108
1107
  'autoCreate',
1109
1108
  this.schema.options,
1110
- conn.config,
1111
- conn.base.options
1109
+ conn.config
1110
+ // No base.options here because we don't want to take the base value if the connection hasn't
1111
+ // set it yet
1112
1112
  );
1113
+ if (autoCreate == null) {
1114
+ // `autoCreate` may later be set when the connection is opened, so wait for connect before checking
1115
+ await conn._waitForConnect(true);
1116
+ autoCreate = utils.getOption(
1117
+ 'autoCreate',
1118
+ this.schema.options,
1119
+ conn.config,
1120
+ conn.base.options
1121
+ );
1122
+ }
1123
+
1113
1124
  if (!autoCreate) {
1114
1125
  return;
1115
1126
  }
1127
+
1116
1128
  return await this.createCollection();
1117
1129
  };
1118
1130
 
package/lib/query.js CHANGED
@@ -65,6 +65,25 @@ const queryOptionMethods = new Set([
65
65
  'wtimeout'
66
66
  ]);
67
67
 
68
+ // Map from operation name to the name of the function that executes the actual operation against MongoDB.
69
+ // Called a thunk for legacy reasons, "thunk" means function that takes exactly 1 param, a callback.
70
+ // Currently `_countDocuments()`, etc. are async functions that take no params.
71
+ const opToThunk = new Map([
72
+ ['countDocuments', '_countDocuments'],
73
+ ['distinct', '__distinct'],
74
+ ['estimatedDocumentCount', '_estimatedDocumentCount'],
75
+ ['find', '_find'],
76
+ ['findOne', '_findOne'],
77
+ ['findOneAndReplace', '_findOneAndReplace'],
78
+ ['findOneAndUpdate', '_findOneAndUpdate'],
79
+ ['replaceOne', '_replaceOne'],
80
+ ['updateMany', '_updateMany'],
81
+ ['updateOne', '_updateOne'],
82
+ ['deleteMany', '_deleteMany'],
83
+ ['deleteOne', '_deleteOne'],
84
+ ['findOneAndDelete', '_findOneAndDelete']
85
+ ]);
86
+
68
87
  /**
69
88
  * Query constructor used for building queries. You do not need
70
89
  * to instantiate a `Query` directly. Instead use Model functions like
@@ -2337,18 +2356,17 @@ Query.prototype._find = async function _find() {
2337
2356
  }
2338
2357
 
2339
2358
  const mongooseOptions = this._mongooseOptions;
2340
- const _this = this;
2341
- const userProvidedFields = _this._userProvidedFields || {};
2359
+ const userProvidedFields = this._userProvidedFields || {};
2342
2360
 
2343
2361
  applyGlobalMaxTimeMS(this.options, this.model.db.options, this.model.base.options);
2344
2362
  applyGlobalDiskUse(this.options, this.model.db.options, this.model.base.options);
2345
2363
 
2346
2364
  // Separate options to pass down to `completeMany()` in case we need to
2347
2365
  // set a session on the document
2348
- const completeManyOptions = Object.assign({}, {
2366
+ const completeManyOptions = {
2349
2367
  session: this && this.options && this.options.session || null,
2350
2368
  lean: mongooseOptions.lean || null
2351
- });
2369
+ };
2352
2370
 
2353
2371
  const options = this._optionsForExec();
2354
2372
 
@@ -2366,7 +2384,7 @@ Query.prototype._find = async function _find() {
2366
2384
  }
2367
2385
 
2368
2386
  if (!mongooseOptions.populate) {
2369
- const versionKey = _this.schema.options.versionKey;
2387
+ const versionKey = this.schema.options.versionKey;
2370
2388
  if (mongooseOptions.lean && mongooseOptions.lean.versionKey === false && versionKey) {
2371
2389
  docs.forEach((doc) => {
2372
2390
  if (versionKey in doc) {
@@ -2375,17 +2393,17 @@ Query.prototype._find = async function _find() {
2375
2393
  });
2376
2394
  }
2377
2395
  return mongooseOptions.lean ?
2378
- _completeManyLean(_this.model.schema, docs, null, completeManyOptions) :
2379
- _this._completeMany(docs, fields, userProvidedFields, completeManyOptions);
2396
+ _completeManyLean(this.model.schema, docs, null, completeManyOptions) :
2397
+ this._completeMany(docs, fields, userProvidedFields, completeManyOptions);
2380
2398
  }
2381
2399
 
2382
- const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions);
2400
+ const pop = helpers.preparePopulationOptionsMQ(this, mongooseOptions);
2383
2401
 
2384
2402
  if (mongooseOptions.lean) {
2385
- return _this.model.populate(docs, pop);
2403
+ return this.model.populate(docs, pop);
2386
2404
  }
2387
2405
 
2388
- docs = await _this._completeMany(docs, fields, userProvidedFields, completeManyOptions);
2406
+ docs = await this._completeMany(docs, fields, userProvidedFields, completeManyOptions);
2389
2407
  await this.model.populate(docs, pop);
2390
2408
 
2391
2409
  return docs;
@@ -4397,22 +4415,14 @@ Query.prototype.exec = async function exec(op) {
4397
4415
  if (this.model == null) {
4398
4416
  throw new MongooseError('Query must have an associated model before executing');
4399
4417
  }
4400
- this._validateOp();
4401
-
4402
- if (!this.op) {
4403
- return;
4404
- }
4405
4418
 
4406
- if (this.options && this.options.sort) {
4407
- const keys = Object.keys(this.options.sort);
4408
- if (keys.includes('')) {
4409
- throw new Error('Invalid field "" passed to sort()');
4410
- }
4419
+ const thunk = opToThunk.get(this.op);
4420
+ if (!thunk) {
4421
+ throw new MongooseError('Query has invalid `op`: "' + this.op + '"');
4411
4422
  }
4412
4423
 
4413
- let thunk = '_' + this.op;
4414
- if (this.op === 'distinct') {
4415
- thunk = '__distinct';
4424
+ if (this.options && this.options.sort && typeof this.options.sort === 'object' && this.options.sort.hasOwnProperty('')) {
4425
+ throw new Error('Invalid field "" passed to sort()');
4416
4426
  }
4417
4427
 
4418
4428
  if (this._executionStack != null) {
package/lib/schema/map.js CHANGED
@@ -91,14 +91,7 @@ class SchemaMap extends SchemaType {
91
91
 
92
92
  const isRequired = this.options.required && typeof this.options.required !== 'function';
93
93
  const result = createJSONSchemaTypeDefinition('object', 'object', useBsonType, isRequired);
94
-
95
- if (embeddedSchemaType.schema) {
96
- result.additionalProperties = useBsonType
97
- ? { ...embeddedSchemaType.toJSONSchema(options) }
98
- : { ...embeddedSchemaType.toJSONSchema(options) };
99
- } else {
100
- result.additionalProperties = embeddedSchemaType.toJSONSchema(options);
101
- }
94
+ result.additionalProperties = embeddedSchemaType.toJSONSchema(options);
102
95
 
103
96
  return result;
104
97
  }
package/lib/schema.js CHANGED
@@ -1118,6 +1118,9 @@ Schema.prototype.path = function(path, obj) {
1118
1118
  this.paths[path] = this.interpretAsType(path, obj, this.options);
1119
1119
  const schemaType = this.paths[path];
1120
1120
 
1121
+ // If overwriting an existing path, make sure to clear the childSchemas
1122
+ this.childSchemas = this.childSchemas.filter(childSchema => childSchema.path !== path);
1123
+
1121
1124
  if (schemaType.$isSchemaMap) {
1122
1125
  // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
1123
1126
  // The '$' is to imply this path should never be stored in MongoDB so we
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "8.10.0",
4
+ "version": "8.10.1",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
package/types/index.d.ts CHANGED
@@ -273,10 +273,10 @@ declare module 'mongoose' {
273
273
  /**
274
274
  * Create a new schema
275
275
  */
276
- constructor(definition?: SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType> | DocType, options?: SchemaOptions<FlatRecord<DocType>, TInstanceMethods, TQueryHelpers, TStaticMethods, TVirtuals, THydratedDocumentType> | ResolveSchemaOptions<TSchemaOptions>);
276
+ constructor(definition?: SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType, THydratedDocumentType> | DocType, options?: SchemaOptions<FlatRecord<DocType>, TInstanceMethods, TQueryHelpers, TStaticMethods, TVirtuals, THydratedDocumentType> | ResolveSchemaOptions<TSchemaOptions>);
277
277
 
278
278
  /** Adds key path / schema type pairs to this schema. */
279
- add(obj: SchemaDefinition<SchemaDefinitionType<RawDocType>> | Schema, prefix?: string): this;
279
+ add(obj: SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType> | Schema, prefix?: string): this;
280
280
 
281
281
  /**
282
282
  * Add an alias for `path`. This means getting or setting the `alias`
@@ -297,7 +297,7 @@ declare module 'mongoose' {
297
297
  /** Returns a copy of this schema */
298
298
  clone<T = this>(): T;
299
299
 
300
- discriminator<DisSchema = Schema>(name: string | number, schema: DisSchema): this;
300
+ discriminator<DisSchema = Schema>(name: string | number, schema: DisSchema, options?: DiscriminatorOptions): this;
301
301
 
302
302
  /** Returns a new schema that has the picked `paths` from this schema. */
303
303
  pick<T = this>(paths: string[], options?: SchemaOptions): T;
@@ -541,21 +541,21 @@ declare module 'mongoose' {
541
541
  ? DateSchemaDefinition
542
542
  : (Function | string);
543
543
 
544
- export type SchemaDefinitionProperty<T = undefined, EnforcedDocType = any> = SchemaDefinitionWithBuiltInClass<T> |
545
- SchemaTypeOptions<T extends undefined ? any : T, EnforcedDocType> |
546
- typeof SchemaType |
547
- Schema<any, any, any> |
548
- Schema<any, any, any>[] |
549
- SchemaTypeOptions<T extends undefined ? any : Unpacked<T>, EnforcedDocType>[] |
550
- Function[] |
551
- SchemaDefinition<T, EnforcedDocType> |
552
- SchemaDefinition<Unpacked<T>, EnforcedDocType>[] |
553
- typeof Schema.Types.Mixed |
554
- MixedSchemaTypeOptions<EnforcedDocType>;
555
-
556
- export type SchemaDefinition<T = undefined, EnforcedDocType = any> = T extends undefined
544
+ export type SchemaDefinitionProperty<T = undefined, EnforcedDocType = any, THydratedDocumentType = HydratedDocument<EnforcedDocType>> = SchemaDefinitionWithBuiltInClass<T>
545
+ | SchemaTypeOptions<T extends undefined ? any : T, EnforcedDocType, THydratedDocumentType>
546
+ | typeof SchemaType
547
+ | Schema<any, any, any>
548
+ | Schema<any, any, any>[]
549
+ | SchemaTypeOptions<T extends undefined ? any : Unpacked<T>, EnforcedDocType, THydratedDocumentType>[]
550
+ | Function[]
551
+ | SchemaDefinition<T, EnforcedDocType, THydratedDocumentType>
552
+ | SchemaDefinition<Unpacked<T>, EnforcedDocType, THydratedDocumentType>[]
553
+ | typeof Schema.Types.Mixed
554
+ | MixedSchemaTypeOptions<EnforcedDocType>;
555
+
556
+ export type SchemaDefinition<T = undefined, EnforcedDocType = any, THydratedDocumentType = HydratedDocument<EnforcedDocType>> = T extends undefined
557
557
  ? { [path: string]: SchemaDefinitionProperty; }
558
- : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType>; };
558
+ : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType, THydratedDocumentType>; };
559
559
 
560
560
  export type AnyArray<T> = T[] | ReadonlyArray<T>;
561
561
  export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
@@ -56,7 +56,7 @@ declare module 'mongoose' {
56
56
 
57
57
  type DefaultType<T> = T extends Schema.Types.Mixed ? any : Partial<ExtractMongooseArray<T>>;
58
58
 
59
- class SchemaTypeOptions<T, EnforcedDocType = any> {
59
+ class SchemaTypeOptions<T, EnforcedDocType = any, THydratedDocumentType = HydratedDocument<EnforcedDocType>> {
60
60
  type?:
61
61
  T extends string ? StringSchemaDefinition :
62
62
  T extends number ? NumberSchemaDefinition :
@@ -65,19 +65,19 @@ declare module 'mongoose' {
65
65
  T extends Map<any, any> ? SchemaDefinition<typeof Map> :
66
66
  T extends Buffer ? SchemaDefinition<typeof Buffer> :
67
67
  T extends Types.ObjectId ? ObjectIdSchemaDefinition :
68
- T extends Types.ObjectId[] ? AnyArray<ObjectIdSchemaDefinition> | AnyArray<SchemaTypeOptions<ObjectId, EnforcedDocType>> :
69
- T extends object[] ? (AnyArray<Schema<any, any, any>> | AnyArray<SchemaDefinition<Unpacked<T>>> | AnyArray<SchemaTypeOptions<Unpacked<T>, EnforcedDocType>>) :
70
- T extends string[] ? AnyArray<StringSchemaDefinition> | AnyArray<SchemaTypeOptions<string, EnforcedDocType>> :
71
- T extends number[] ? AnyArray<NumberSchemaDefinition> | AnyArray<SchemaTypeOptions<number, EnforcedDocType>> :
72
- T extends boolean[] ? AnyArray<BooleanSchemaDefinition> | AnyArray<SchemaTypeOptions<boolean, EnforcedDocType>> :
73
- T extends Function[] ? AnyArray<Function | string> | AnyArray<SchemaTypeOptions<Unpacked<T>, EnforcedDocType>> :
68
+ T extends Types.ObjectId[] ? AnyArray<ObjectIdSchemaDefinition> | AnyArray<SchemaTypeOptions<ObjectId, EnforcedDocType, THydratedDocumentType>> :
69
+ T extends object[] ? (AnyArray<Schema<any, any, any>> | AnyArray<SchemaDefinition<Unpacked<T>>> | AnyArray<SchemaTypeOptions<Unpacked<T>, EnforcedDocType, THydratedDocumentType>>) :
70
+ T extends string[] ? AnyArray<StringSchemaDefinition> | AnyArray<SchemaTypeOptions<string, EnforcedDocType, THydratedDocumentType>> :
71
+ T extends number[] ? AnyArray<NumberSchemaDefinition> | AnyArray<SchemaTypeOptions<number, EnforcedDocType, THydratedDocumentType>> :
72
+ T extends boolean[] ? AnyArray<BooleanSchemaDefinition> | AnyArray<SchemaTypeOptions<boolean, EnforcedDocType, THydratedDocumentType>> :
73
+ T extends Function[] ? AnyArray<Function | string> | AnyArray<SchemaTypeOptions<Unpacked<T>, EnforcedDocType, THydratedDocumentType>> :
74
74
  T | typeof SchemaType | Schema<any, any, any> | SchemaDefinition<T> | Function | AnyArray<Function>;
75
75
 
76
76
  /** Defines a virtual with the given name that gets/sets this path. */
77
77
  alias?: string | string[];
78
78
 
79
79
  /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */
80
- validate?: SchemaValidator<T, EnforcedDocType> | AnyArray<SchemaValidator<T, EnforcedDocType>>;
80
+ validate?: SchemaValidator<T, EnforcedDocType, THydratedDocumentType> | AnyArray<SchemaValidator<T, EnforcedDocType, THydratedDocumentType>>;
81
81
 
82
82
  /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
83
83
  cast?: string |
@@ -389,10 +389,10 @@ declare module 'mongoose' {
389
389
  expires(when: number | string): this;
390
390
 
391
391
  /** Sets a maximum date validator. */
392
- max(value: NativeDate, message: string): this;
392
+ max(value: NativeDate, message?: string): this;
393
393
 
394
394
  /** Sets a minimum date validator. */
395
- min(value: NativeDate, message: string): this;
395
+ min(value: NativeDate, message?: string): this;
396
396
 
397
397
  /** Default options for this SchemaType */
398
398
  defaultOptions: Record<string, any>;
@@ -457,10 +457,10 @@ declare module 'mongoose' {
457
457
  enum(vals: number[]): this;
458
458
 
459
459
  /** Sets a maximum number validator. */
460
- max(value: number, message: string): this;
460
+ max(value: number, message?: string): this;
461
461
 
462
462
  /** Sets a minimum number validator. */
463
- min(value: number, message: string): this;
463
+ min(value: number, message?: string): this;
464
464
 
465
465
  /** Default options for this SchemaType */
466
466
  defaultOptions: Record<string, any>;
@@ -1,6 +1,11 @@
1
1
  declare module 'mongoose' {
2
2
 
3
- type SchemaValidator<T, EnforcedDocType> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T, EnforcedDocType> | ValidateOpts<T, EnforcedDocType>[];
3
+ type SchemaValidator<T, EnforcedDocType, THydratedDocumentType> = RegExp
4
+ | [RegExp, string]
5
+ | Function
6
+ | [Function, string]
7
+ | ValidateOpts<T, THydratedDocumentType>
8
+ | ValidateOpts<T, THydratedDocumentType>[];
4
9
 
5
10
  interface ValidatorProps {
6
11
  path: string;