mongoose 8.9.7 → 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/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
@@ -1939,13 +1942,11 @@ Schema.prototype.pre = function(name) {
1939
1942
  * const Model = mongoose.model('Model', schema);
1940
1943
  *
1941
1944
  * const m = new Model(..);
1942
- * m.save(function(err) {
1943
- * console.log('this fires after the `post` hook');
1944
- * });
1945
+ * await m.save();
1946
+ * console.log('this fires after the `post` hook');
1945
1947
  *
1946
- * m.find(function(err, docs) {
1947
- * console.log('this fires after the post find hook');
1948
- * });
1948
+ * await m.find();
1949
+ * console.log('this fires after the post find hook');
1949
1950
  *
1950
1951
  * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1951
1952
  * @param {Object} [options]
@@ -2382,9 +2383,15 @@ Schema.prototype.virtual = function(name, options) {
2382
2383
  const PopulateModel = this.db.model(modelNames[0]);
2383
2384
  for (let i = 0; i < populatedVal.length; ++i) {
2384
2385
  if (!populatedVal[i].$__) {
2385
- populatedVal[i] = PopulateModel.hydrate(populatedVal[i]);
2386
+ populatedVal[i] = PopulateModel.hydrate(populatedVal[i], null, { hydratedPopulatedDocs: true });
2386
2387
  }
2387
2388
  }
2389
+ const foreignField = options.foreignField;
2390
+ this.$populated(
2391
+ name,
2392
+ populatedVal.map(doc => doc == null ? doc : doc.get(typeof foreignField === 'function' ? foreignField.call(doc, doc) : foreignField)),
2393
+ { populateModelSymbol: PopulateModel }
2394
+ );
2388
2395
  }
2389
2396
  }
2390
2397
 
@@ -2882,6 +2889,92 @@ Schema.prototype._preCompile = function _preCompile() {
2882
2889
  this.plugin(idGetter, { deduplicate: true });
2883
2890
  };
2884
2891
 
2892
+ /**
2893
+ * Returns a JSON schema representation of this Schema.
2894
+ *
2895
+ * By default, returns normal [JSON schema representation](https://json-schema.org/learn/getting-started-step-by-step), which is not typically what you want to use with
2896
+ * [MongoDB's `$jsonSchema` collection option](https://www.mongodb.com/docs/manual/core/schema-validation/specify-json-schema/).
2897
+ * Use the `useBsonType: true` option to return MongoDB `$jsonSchema` syntax instead.
2898
+ *
2899
+ * In addition to types, `jsonSchema()` supports the following Mongoose validators:
2900
+ * - `enum` for strings and numbers
2901
+ *
2902
+ * #### Example:
2903
+ * const schema = new Schema({ name: String });
2904
+ * // { required: ['_id'], properties: { name: { type: ['string', 'null'] }, _id: { type: 'string' } } }
2905
+ * schema.toJSONSchema();
2906
+ *
2907
+ * // { required: ['_id'], properties: { name: { bsonType: ['string', 'null'] }, _id: { bsonType: 'objectId' } } }
2908
+ * schema.toJSONSchema({ useBsonType: true });
2909
+ *
2910
+ * @param {Object} [options]
2911
+ * @param [Boolean] [options.useBsonType=false] if true, specify each path's type using `bsonType` rather than `type` for MongoDB $jsonSchema support
2912
+ */
2913
+
2914
+ Schema.prototype.toJSONSchema = function toJSONSchema(options) {
2915
+ const useBsonType = options?.useBsonType ?? false;
2916
+ const result = useBsonType ? { required: [], properties: {} } : { type: 'object', required: [], properties: {} };
2917
+ for (const path of Object.keys(this.paths)) {
2918
+ const schemaType = this.paths[path];
2919
+
2920
+ // Skip Map embedded paths, maps will be handled seperately.
2921
+ if (schemaType._presplitPath.indexOf('$*') !== -1) {
2922
+ continue;
2923
+ }
2924
+
2925
+ // Nested paths are stored as `nested.path` in the schema type, so create nested paths in the json schema
2926
+ // when necessary.
2927
+ const isNested = schemaType._presplitPath.length > 1;
2928
+ let jsonSchemaForPath = result;
2929
+ if (isNested) {
2930
+ for (let i = 0; i < schemaType._presplitPath.length - 1; ++i) {
2931
+ const subpath = schemaType._presplitPath[i];
2932
+ if (jsonSchemaForPath.properties[subpath] == null) {
2933
+ jsonSchemaForPath.properties[subpath] = useBsonType
2934
+ ? {
2935
+ bsonType: ['object', 'null'],
2936
+ properties: {}
2937
+ }
2938
+ : {
2939
+ type: ['object', 'null'],
2940
+ properties: {}
2941
+ };
2942
+ }
2943
+ jsonSchemaForPath = jsonSchemaForPath.properties[subpath];
2944
+ }
2945
+ }
2946
+
2947
+ const lastSubpath = schemaType._presplitPath[schemaType._presplitPath.length - 1];
2948
+ let isRequired = false;
2949
+ if (path === '_id') {
2950
+ if (!jsonSchemaForPath.required) {
2951
+ jsonSchemaForPath.required = [];
2952
+ }
2953
+ jsonSchemaForPath.required.push('_id');
2954
+ isRequired = true;
2955
+ } else if (schemaType.options.required && typeof schemaType.options.required !== 'function') {
2956
+ if (!jsonSchemaForPath.required) {
2957
+ jsonSchemaForPath.required = [];
2958
+ }
2959
+ // Only `required: true` paths are required, conditional required is not required
2960
+ jsonSchemaForPath.required.push(lastSubpath);
2961
+ isRequired = true;
2962
+ }
2963
+ jsonSchemaForPath.properties[lastSubpath] = schemaType.toJSONSchema(options);
2964
+ if (schemaType.options.enum) {
2965
+ jsonSchemaForPath.properties[lastSubpath].enum = isRequired
2966
+ ? schemaType.options.enum
2967
+ : [...schemaType.options.enum, null];
2968
+ }
2969
+ }
2970
+
2971
+ // Otherwise MongoDB errors with "$jsonSchema keyword 'required' cannot be an empty array"
2972
+ if (result.required.length === 0) {
2973
+ delete result.required;
2974
+ }
2975
+ return result;
2976
+ };
2977
+
2885
2978
  /*!
2886
2979
  * Module exports.
2887
2980
  */
package/lib/schemaType.js CHANGED
@@ -1555,7 +1555,7 @@ SchemaType._isRef = function(self, value, doc, init) {
1555
1555
  * ignore
1556
1556
  */
1557
1557
 
1558
- SchemaType.prototype._castRef = function _castRef(value, doc, init) {
1558
+ SchemaType.prototype._castRef = function _castRef(value, doc, init, options) {
1559
1559
  if (value == null) {
1560
1560
  return value;
1561
1561
  }
@@ -1587,7 +1587,7 @@ SchemaType.prototype._castRef = function _castRef(value, doc, init) {
1587
1587
  !doc.$__.populated[path].options.options ||
1588
1588
  !doc.$__.populated[path].options.options.lean) {
1589
1589
  const PopulatedModel = pop ? pop.options[populateModelSymbol] : doc.constructor.db.model(this.options.ref);
1590
- ret = new PopulatedModel(value);
1590
+ ret = PopulatedModel.hydrate(value, null, options);
1591
1591
  ret.$__.wasPopulated = { value: ret._doc._id, options: { [populateModelSymbol]: PopulatedModel } };
1592
1592
  }
1593
1593
 
@@ -1771,6 +1771,18 @@ SchemaType.prototype.getEmbeddedSchemaType = function getEmbeddedSchemaType() {
1771
1771
 
1772
1772
  SchemaType.prototype._duplicateKeyErrorMessage = null;
1773
1773
 
1774
+ /**
1775
+ * Returns this schema type's representation in a JSON schema.
1776
+ *
1777
+ * @param [options]
1778
+ * @param [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
1779
+ * @returns {Object} JSON schema properties
1780
+ */
1781
+
1782
+ SchemaType.prototype.toJSONSchema = function toJSONSchema() {
1783
+ throw new Error('Converting unsupported SchemaType to JSON Schema: ' + this.instance);
1784
+ };
1785
+
1774
1786
  /*!
1775
1787
  * Module exports.
1776
1788
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "8.9.7",
4
+ "version": "8.10.1",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -17,11 +17,12 @@
17
17
  "orm",
18
18
  "db"
19
19
  ],
20
+ "type": "commonjs",
20
21
  "license": "MIT",
21
22
  "dependencies": {
22
23
  "bson": "^6.10.1",
23
24
  "kareem": "2.6.3",
24
- "mongodb": "~6.12.0",
25
+ "mongodb": "~6.13.0",
25
26
  "mpath": "0.9.0",
26
27
  "mquery": "5.0.0",
27
28
  "ms": "2.1.3",
@@ -35,6 +36,7 @@
35
36
  "acquit": "1.3.0",
36
37
  "acquit-ignore": "0.2.1",
37
38
  "acquit-require": "0.1.1",
39
+ "ajv": "8.17.1",
38
40
  "assert-browserify": "2.0.0",
39
41
  "babel-loader": "8.2.5",
40
42
  "broken-link-checker": "^0.7.8",
@@ -102,6 +104,8 @@
102
104
  "test-deno": "deno run --allow-env --allow-read --allow-net --allow-run --allow-sys --allow-write ./test/deno.js",
103
105
  "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
104
106
  "test-tsd": "node ./test/types/check-types-filename && tsd",
107
+ "setup-test-encryption": "bash scripts/configure-cluster-with-encryption.sh",
108
+ "test-encryption": "mocha --exit ./test/encryption/*.test.js",
105
109
  "tdd": "mocha ./test/*.test.js --inspect --watch --recursive --watch-files ./**/*.{js,ts}",
106
110
  "test-coverage": "nyc --reporter=html --reporter=text npm test",
107
111
  "ts-benchmark": "cd ./benchmarks/typescript/simple && npm install && npm run benchmark | node ../../../scripts/tsc-diagnostics-check"
@@ -59,6 +59,8 @@ declare module 'mongoose' {
59
59
  }
60
60
 
61
61
  class Connection extends events.EventEmitter implements SessionStarter {
62
+ aggregate<ResultType = unknown>(pipeline?: PipelineStage[] | null, options?: AggregateOptions): Aggregate<Array<ResultType>>;
63
+
62
64
  /** Returns a promise that resolves when this connection successfully connects to MongoDB */
63
65
  asPromise(): Promise<this>;
64
66
 
@@ -256,21 +256,21 @@ declare module 'mongoose' {
256
256
  set(value: string | Record<string, any>): this;
257
257
 
258
258
  /** The return value of this method is used in calls to JSON.stringify(doc). */
259
- toJSON(options?: ToObjectOptions & { flattenMaps?: true, flattenObjectIds?: false }): FlattenMaps<Require_id<DocType>>;
260
- toJSON(options: ToObjectOptions & { flattenObjectIds: false }): FlattenMaps<Require_id<DocType>>;
261
- toJSON(options: ToObjectOptions & { flattenObjectIds: true }): ObjectIdToString<FlattenMaps<Require_id<DocType>>>;
262
- toJSON(options: ToObjectOptions & { flattenMaps: false }): Require_id<DocType>;
263
- toJSON(options: ToObjectOptions & { flattenMaps: false; flattenObjectIds: true }): ObjectIdToString<Require_id<DocType>>;
264
-
265
- toJSON<T = Require_id<DocType>>(options?: ToObjectOptions & { flattenMaps?: true, flattenObjectIds?: false }): FlattenMaps<T>;
266
- toJSON<T = Require_id<DocType>>(options: ToObjectOptions & { flattenObjectIds: false }): FlattenMaps<T>;
267
- toJSON<T = Require_id<DocType>>(options: ToObjectOptions & { flattenObjectIds: true }): ObjectIdToString<FlattenMaps<T>>;
268
- toJSON<T = Require_id<DocType>>(options: ToObjectOptions & { flattenMaps: false }): T;
269
- toJSON<T = Require_id<DocType>>(options: ToObjectOptions & { flattenMaps: false; flattenObjectIds: true }): ObjectIdToString<T>;
259
+ toJSON(options?: ToObjectOptions & { flattenMaps?: true, flattenObjectIds?: false }): FlattenMaps<Default__v<Require_id<DocType>>>;
260
+ toJSON(options: ToObjectOptions & { flattenObjectIds: false }): FlattenMaps<Default__v<Require_id<DocType>>>;
261
+ toJSON(options: ToObjectOptions & { flattenObjectIds: true }): ObjectIdToString<FlattenMaps<Default__v<Require_id<DocType>>>>;
262
+ toJSON(options: ToObjectOptions & { flattenMaps: false }): Default__v<Require_id<DocType>>;
263
+ toJSON(options: ToObjectOptions & { flattenMaps: false; flattenObjectIds: true }): ObjectIdToString<Default__v<Require_id<DocType>>>;
264
+
265
+ toJSON<T = Default__v<Require_id<DocType>>>(options?: ToObjectOptions & { flattenMaps?: true, flattenObjectIds?: false }): FlattenMaps<T>;
266
+ toJSON<T = Default__v<Require_id<DocType>>>(options: ToObjectOptions & { flattenObjectIds: false }): FlattenMaps<T>;
267
+ toJSON<T = Default__v<Require_id<DocType>>>(options: ToObjectOptions & { flattenObjectIds: true }): ObjectIdToString<FlattenMaps<T>>;
268
+ toJSON<T = Default__v<Require_id<DocType>>>(options: ToObjectOptions & { flattenMaps: false }): T;
269
+ toJSON<T = Default__v<Require_id<DocType>>>(options: ToObjectOptions & { flattenMaps: false; flattenObjectIds: true }): ObjectIdToString<T>;
270
270
 
271
271
  /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
272
- toObject(options?: ToObjectOptions): Require_id<DocType>;
273
- toObject<T>(options?: ToObjectOptions): Require_id<T>;
272
+ toObject(options?: ToObjectOptions): Default__v<Require_id<DocType>>;
273
+ toObject<T>(options?: ToObjectOptions): Default__v<Require_id<T>>;
274
274
 
275
275
  /** Clears the modified state on the specified path. */
276
276
  unmarkModified<T extends keyof DocType>(path: T): void;
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;
@@ -508,6 +508,8 @@ declare module 'mongoose' {
508
508
  statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } &
509
509
  { [name: string]: (this: TModelType, ...args: any[]) => unknown };
510
510
 
511
+ toJSONSchema(options?: { useBsonType?: boolean }): Record<string, any>;
512
+
511
513
  /** Creates a virtual type with the given name. */
512
514
  virtual<T = HydratedDocument<DocType, TVirtuals & TInstanceMethods, TQueryHelpers>>(
513
515
  name: keyof TVirtuals | string,
@@ -539,21 +541,21 @@ declare module 'mongoose' {
539
541
  ? DateSchemaDefinition
540
542
  : (Function | string);
541
543
 
542
- export type SchemaDefinitionProperty<T = undefined, EnforcedDocType = any> = SchemaDefinitionWithBuiltInClass<T> |
543
- SchemaTypeOptions<T extends undefined ? any : T, EnforcedDocType> |
544
- typeof SchemaType |
545
- Schema<any, any, any> |
546
- Schema<any, any, any>[] |
547
- SchemaTypeOptions<T extends undefined ? any : Unpacked<T>, EnforcedDocType>[] |
548
- Function[] |
549
- SchemaDefinition<T, EnforcedDocType> |
550
- SchemaDefinition<Unpacked<T>, EnforcedDocType>[] |
551
- typeof Schema.Types.Mixed |
552
- MixedSchemaTypeOptions<EnforcedDocType>;
553
-
554
- 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
555
557
  ? { [path: string]: SchemaDefinitionProperty; }
556
- : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType>; };
558
+ : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType, THydratedDocumentType>; };
557
559
 
558
560
  export type AnyArray<T> = T[] | ReadonlyArray<T>;
559
561
  export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
@@ -827,7 +829,7 @@ declare module 'mongoose' {
827
829
  ? Types.DocumentArray<FlattenMaps<ItemType>> : FlattenMaps<T>;
828
830
 
829
831
  export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
830
- export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function | mongodb.Binary;
832
+ export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function | mongodb.Binary | mongodb.ClientSession;
831
833
 
832
834
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
833
835
 
package/types/models.d.ts CHANGED
@@ -577,6 +577,13 @@ declare module 'mongoose' {
577
577
  Array<MergeType<THydratedDocumentType, Omit<DocContents, '_id'>>>
578
578
  >;
579
579
 
580
+ /**
581
+ * Shortcut for saving one document to the database.
582
+ * `MyModel.insertOne(obj, options)` is almost equivalent to `new MyModel(obj).save(options)`.
583
+ * The difference is that `insertOne()` checks if `obj` is already a document, and checks for discriminators.
584
+ */
585
+ insertOne<DocContents = AnyKeys<TRawDocType>>(doc: DocContents | TRawDocType, options?: SaveOptions): Promise<THydratedDocumentType>;
586
+
580
587
  /**
581
588
  * List all [Atlas search indexes](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) on this model's collection.
582
589
  * This function only works when connected to MongoDB Atlas.
@@ -608,6 +615,13 @@ declare module 'mongoose' {
608
615
  */
609
616
  updateSearchIndex(name: string, definition: AnyObject): Promise<void>;
610
617
 
618
+ /**
619
+ * Changes the Connection instance this model uses to make requests to MongoDB.
620
+ * This function is most useful for changing the Connection that a Model defined using `mongoose.model()` uses
621
+ * after initialization.
622
+ */
623
+ useConnection(connection: Connection): this;
624
+
611
625
  /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
612
626
  validate(): Promise<void>;
613
627
  validate(obj: any): Promise<void>;
@@ -869,17 +883,20 @@ declare module 'mongoose' {
869
883
 
870
884
  /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
871
885
  updateMany<ResultDoc = THydratedDocumentType>(
872
- filter?: RootFilterQuery<TRawDocType>,
873
- update?: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,
886
+ filter: RootFilterQuery<TRawDocType>,
887
+ update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,
874
888
  options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null
875
889
  ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, TRawDocType, 'updateMany', TInstanceMethods & TVirtuals>;
876
890
 
877
891
  /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */
878
892
  updateOne<ResultDoc = THydratedDocumentType>(
879
- filter?: RootFilterQuery<TRawDocType>,
880
- update?: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,
893
+ filter: RootFilterQuery<TRawDocType>,
894
+ update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,
881
895
  options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null
882
896
  ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, TRawDocType, 'updateOne', TInstanceMethods & TVirtuals>;
897
+ updateOne<ResultDoc = THydratedDocumentType>(
898
+ update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline
899
+ ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, TRawDocType, 'updateOne', TInstanceMethods & TVirtuals>;
883
900
 
884
901
  /** Creates a Query, applies the passed conditions, and returns the Query. */
885
902
  where<ResultDoc = THydratedDocumentType>(
package/types/query.d.ts CHANGED
@@ -850,20 +850,26 @@ declare module 'mongoose' {
850
850
  * the `multi` option.
851
851
  */
852
852
  updateMany(
853
- filter?: RootFilterQuery<RawDocType>,
854
- update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
853
+ filter: RootFilterQuery<RawDocType>,
854
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
855
855
  options?: QueryOptions<DocType> | null
856
856
  ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateMany', TDocOverrides>;
857
+ updateMany(
858
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline
859
+ ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateMany', TDocOverrides>;
857
860
 
858
861
  /**
859
862
  * Declare and/or execute this query as an updateOne() operation. Same as
860
863
  * `update()`, except it does not support the `multi` or `overwrite` options.
861
864
  */
862
865
  updateOne(
863
- filter?: RootFilterQuery<RawDocType>,
864
- update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
866
+ filter: RootFilterQuery<RawDocType>,
867
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
865
868
  options?: QueryOptions<DocType> | null
866
869
  ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateOne', TDocOverrides>;
870
+ updateOne(
871
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline
872
+ ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateOne', TDocOverrides>;
867
873
 
868
874
  /**
869
875
  * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
@@ -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 |
@@ -300,6 +300,8 @@ declare module 'mongoose' {
300
300
  /** Declares a full text index. */
301
301
  text(bool: boolean): this;
302
302
 
303
+ toJSONSchema(options?: { useBsonType?: boolean }): Record<string, any>;
304
+
303
305
  /** Defines a custom function for transforming this path when converting a document to JSON. */
304
306
  transform(fn: (value: any) => any): this;
305
307
 
@@ -387,10 +389,10 @@ declare module 'mongoose' {
387
389
  expires(when: number | string): this;
388
390
 
389
391
  /** Sets a maximum date validator. */
390
- max(value: NativeDate, message: string): this;
392
+ max(value: NativeDate, message?: string): this;
391
393
 
392
394
  /** Sets a minimum date validator. */
393
- min(value: NativeDate, message: string): this;
395
+ min(value: NativeDate, message?: string): this;
394
396
 
395
397
  /** Default options for this SchemaType */
396
398
  defaultOptions: Record<string, any>;
@@ -455,10 +457,10 @@ declare module 'mongoose' {
455
457
  enum(vals: number[]): this;
456
458
 
457
459
  /** Sets a maximum number validator. */
458
- max(value: number, message: string): this;
460
+ max(value: number, message?: string): this;
459
461
 
460
462
  /** Sets a minimum number validator. */
461
- min(value: number, message: string): this;
463
+ min(value: number, message?: string): this;
462
464
 
463
465
  /** Default options for this SchemaType */
464
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;