@depup/mongoose 9.3.3-depup.0 → 9.8.0-depup.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.
Files changed (73) hide show
  1. package/README.md +3 -9
  2. package/changes.json +3 -8
  3. package/eslint.config.mjs +4 -1
  4. package/lib/aggregate.js +54 -24
  5. package/lib/cast.js +1 -1
  6. package/lib/connection.js +20 -8
  7. package/lib/cursor/aggregationCursor.js +47 -16
  8. package/lib/cursor/queryCursor.js +23 -7
  9. package/lib/document.js +240 -105
  10. package/lib/drivers/node-mongodb-native/collection.js +47 -14
  11. package/lib/drivers/node-mongodb-native/connection.js +13 -0
  12. package/lib/error/cast.js +18 -9
  13. package/lib/error/divergentArray.js +1 -1
  14. package/lib/error/index.js +1 -1
  15. package/lib/error/messages.js +1 -0
  16. package/lib/helpers/clone.js +22 -5
  17. package/lib/helpers/document/applyDefaults.js +5 -0
  18. package/lib/helpers/populate/createPopulateQueryFilter.js +9 -1
  19. package/lib/helpers/populate/getModelsMapForPopulate.js +8 -6
  20. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  21. package/lib/helpers/query/castUpdate.js +4 -0
  22. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  23. package/lib/helpers/update/applyTimestampsToUpdate.js +4 -2
  24. package/lib/model.js +159 -41
  25. package/lib/mongoose.js +3 -3
  26. package/lib/options/schemaTypeOptions.js +14 -0
  27. package/lib/plugins/saveSubdocs.js +16 -13
  28. package/lib/query.js +208 -102
  29. package/lib/queryHelpers.js +13 -12
  30. package/lib/schema/array.js +4 -6
  31. package/lib/schema/bigint.js +1 -3
  32. package/lib/schema/boolean.js +1 -3
  33. package/lib/schema/buffer.js +1 -3
  34. package/lib/schema/date.js +8 -8
  35. package/lib/schema/decimal128.js +1 -3
  36. package/lib/schema/documentArray.js +3 -5
  37. package/lib/schema/double.js +1 -3
  38. package/lib/schema/int32.js +1 -3
  39. package/lib/schema/map.js +1 -4
  40. package/lib/schema/number.js +2 -4
  41. package/lib/schema/objectId.js +7 -3
  42. package/lib/schema/string.js +20 -5
  43. package/lib/schema/subdocument.js +2 -4
  44. package/lib/schema/union.js +50 -0
  45. package/lib/schema/uuid.js +1 -3
  46. package/lib/schema.js +40 -14
  47. package/lib/schemaType.js +93 -12
  48. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  49. package/lib/stateMachine.js +11 -6
  50. package/lib/tracing.js +38 -0
  51. package/lib/types/array/methods/index.js +4 -4
  52. package/lib/types/documentArray/methods/index.js +117 -3
  53. package/lib/types/subdocument.js +4 -2
  54. package/lib/utils.js +12 -2
  55. package/lib/validOptions.js +1 -0
  56. package/package.json +30 -33
  57. package/{tstyche.config.json → tstyche.json} +2 -1
  58. package/types/augmentations.d.ts +2 -2
  59. package/types/document.d.ts +61 -7
  60. package/types/expressions.d.ts +16 -0
  61. package/types/index.d.ts +25 -7
  62. package/types/inferhydrateddoctype.d.ts +1 -1
  63. package/types/inferrawdoctype.d.ts +6 -3
  64. package/types/inferschematype.d.ts +10 -2
  65. package/types/models.d.ts +30 -13
  66. package/types/mongooseoptions.d.ts +9 -1
  67. package/types/populate.d.ts +52 -0
  68. package/types/query.d.ts +39 -12
  69. package/types/schemaoptions.d.ts +5 -0
  70. package/types/schematypes.d.ts +10 -0
  71. package/types/tracing.d.ts +10 -0
  72. package/types/utility.d.ts +11 -2
  73. package/lib/helpers/createJSONSchemaTypeDefinition.js +0 -24
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@depup/mongoose",
3
3
  "description": "Mongoose MongoDB ODM (with updated dependencies)",
4
- "version": "9.3.3-depup.0",
4
+ "version": "9.8.0-depup.0",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongoose",
@@ -26,50 +26,52 @@
26
26
  "type": "commonjs",
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "kareem": "3.2.0",
30
- "mongodb": "^7.1.1",
29
+ "@standard-schema/spec": "^1.1.0",
30
+ "kareem": "3.3.0",
31
+ "mongodb": "~7.5",
31
32
  "mpath": "0.9.0",
32
33
  "mquery": "6.0.0",
33
34
  "ms": "2.1.3",
34
35
  "sift": "17.1.3"
35
36
  },
36
37
  "devDependencies": {
37
- "@ark/attest": "0.56.0",
38
+ "@ark/attest": "0.56.1",
38
39
  "@eslint/js": "^9.39.3",
39
40
  "@mongodb-js/mongodb-downloader": "^1.0.0",
40
- "@types/node": "^18.16.0",
41
+ "@types/node": "^20.19.0",
41
42
  "acquit": "1.4.0",
42
43
  "acquit-ignore": "0.2.2",
43
44
  "acquit-require": "0.1.1",
44
- "ajv": "8.18.0",
45
+ "ajv": "8.20.0",
45
46
  "c8": "11.0.0",
46
- "cheerio": "^1.2",
47
+ "cheerio": "1.2.0",
47
48
  "dox": "1.0.0",
48
- "eslint": "10.0.2",
49
+ "eslint": "10.6.0",
49
50
  "eslint-plugin-mocha-no-only": "1.2.0",
50
- "express": "^4.19.2",
51
+ "express": "5.2.1",
51
52
  "fs-extra": "~11.3.0",
52
- "globals": "^17.4.0",
53
53
  "glob": "^13.0.6",
54
+ "globals": "^17.4.0",
54
55
  "highlight.js": "11.11.1",
55
56
  "linkinator": "7.x",
56
57
  "lodash.isequal": "4.5.0",
57
58
  "lodash.isequalwith": "4.4.0",
58
- "markdownlint-cli2": "^0.21.0",
59
- "marked": "15.x",
59
+ "markdownlint-cli2": "0.22.1",
60
+ "marked": "18.0.5",
60
61
  "mkdirp": "^3.0.1",
61
- "mocha": "11.7.5",
62
+ "mocha": "12.0.0-beta-10",
62
63
  "moment": "2.30.1",
63
- "mongodb-client-encryption": "~7.0",
64
- "mongodb-memory-server": "11.0.1",
64
+ "mongodb-client-encryption": "^7.2.0",
65
+ "mongodb-memory-server": "11.2.0",
65
66
  "mongodb-runner": "^6.0.0",
66
67
  "ncp": "^2.0.0",
67
- "pug": "3.0.3",
68
- "sinon": "21.0.1",
69
- "tstyche": "^6.2.0",
68
+ "pug": "3.0.4",
69
+ "sinon": "22.0.0",
70
+ "tstyche": "^7.0.0",
70
71
  "typescript": "5.9.3",
71
72
  "typescript-eslint": "^8.31.1",
72
- "uuid": "11.1.0"
73
+ "uuid": "14.0.1",
74
+ "xss": "1.0.15"
73
75
  },
74
76
  "directories": {
75
77
  "lib": "./lib/mongoose"
@@ -86,7 +88,7 @@
86
88
  "docs:generate:sponsorData": "node ./scripts/loadSponsorData.js",
87
89
  "docs:test": "npm run docs:generate",
88
90
  "docs:view": "node ./scripts/static.js",
89
- "docs:prepare:publish:stable": "git checkout gh-pages && git merge master && npm run docs:generate",
91
+ "docs:prepare:publish:stable": "git checkout gh-pages && git merge master && env GENERATE_SEARCH=true npm run docs:generate",
90
92
  "docs:prepare:publish:5x": "git checkout 5.x && git merge 5.x && npm run docs:clean:stable && npm run docs:generate && npm run docs:copy:tmp && git checkout gh-pages && npm run docs:copy:tmp:5x",
91
93
  "docs:prepare:publish:6x": "git checkout 6.x && git merge 6.x && npm run docs:clean:stable && env DOCS_DEPLOY=true npm run docs:generate && mv ./docs/6.x ./tmp && git checkout gh-pages && npm run docs:copy:tmp:6x",
92
94
  "docs:prepare:publish:7x": "env DOCS_DEPLOY=true npm run docs:generate && git checkout gh-pages && rm -rf ./docs/7.x && mv ./tmp ./docs/7.x",
@@ -96,24 +98,24 @@
96
98
  "lint": "eslint .",
97
99
  "lint-js": "eslint . --ext .js --ext .cjs",
98
100
  "lint-ts": "eslint . --ext .ts",
99
- "lint-md": "markdownlint-cli2 \"**/*.md\" \"#node_modules\" \"#benchmarks\"",
101
+ "lint-md": "markdownlint-cli2 \"docs/**/*.md\" \"docs/*.md\" \"*.md\"",
100
102
  "release": "git pull && git push origin master --tags && npm publish",
101
103
  "release-5x": "git pull origin 5.x && git push origin 5.x && git push origin 5.x --tags && npm publish --tag 5x",
102
104
  "release-6x": "git pull origin 6.x && git push origin 6.x && git push origin 6.x --tags && npm publish --tag 6x",
103
105
  "mongo": "node ./tools/repl.js",
104
106
  "publish-7x": "npm publish --tag 7x",
105
107
  "create-separate-require-instance": "rm -rf ./node_modules/mongoose-separate-require-instance && node ./scripts/create-tarball && tar -xzf mongoose.tgz -C ./node_modules && mv ./node_modules/package ./node_modules/mongoose-separate-require-instance",
106
- "test": "mocha --exit ./test/*.test.js",
108
+ "test": "mocha --exit --ignore \"test/encryption/**/*.test.js\" \"./test/**/*.test.js\"",
107
109
  "test:ci": "npm run test -- --reporter min",
108
110
  "test-deno": "deno run --allow-env --allow-read --allow-net --allow-run --allow-sys --allow-write ./test/deno.mjs",
109
111
  "test-deno:ci": "npm run test-deno -- --reporter min",
110
- "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
112
+ "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit --ignore \"test/encryption/**/*.test.js\" \"./test/**/*.test.js\"",
111
113
  "test-rs:ci": "npm run test-rs -- --reporter min",
112
114
  "test:types": "tstyche",
113
115
  "setup-test-encryption": "node scripts/setup-encryption-tests.js",
114
116
  "test-encryption": "mocha --exit ./test/encryption/*.test.js",
115
117
  "test-encryption:ci": "npm run test-encryption -- --reporter min",
116
- "tdd": "mocha --watch --inspect --recursive ./test/*.test.js --watch-files lib/**/*.js test/**/*.js",
118
+ "tdd": "mocha --watch --inspect --ignore \"test/encryption/**/*.test.js\" \"./test/**/*.test.js\" --watch-files lib/**/*.js test/**/*.js",
117
119
  "test-coverage": "c8 --reporter=html --reporter=text npm test",
118
120
  "test-coverage:ci": "c8 --reporter=html --reporter=text npm run test:ci",
119
121
  "ts-benchmark": "cd ./benchmarks/typescript/simple && npm install && npm run benchmark | node ../../../scripts/tsc-diagnostics-check",
@@ -143,16 +145,11 @@
143
145
  "url": "https://opencollective.com/mongoose"
144
146
  },
145
147
  "depup": {
146
- "changes": {
147
- "mongodb": {
148
- "from": "~7.1",
149
- "to": "^7.1.1"
150
- }
151
- },
152
- "depsUpdated": 1,
148
+ "changes": {},
149
+ "depsUpdated": 0,
153
150
  "originalPackage": "mongoose",
154
- "originalVersion": "9.3.3",
155
- "processedAt": "2026-03-25T20:16:36.309Z",
151
+ "originalVersion": "9.8.0",
152
+ "processedAt": "2026-07-21T16:17:47.534Z",
156
153
  "smokeTest": "passed"
157
154
  }
158
155
  }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "$schema": "https://tstyche.org/schemas/config.json",
3
3
  "testFileMatch": [
4
- "test/types/*.test.*"
4
+ "test/types/*.test.*",
5
+ "test/types/**/*.test.*"
5
6
  ]
6
7
  }
@@ -1,7 +1,7 @@
1
1
  // this import is required so that types get merged instead of completely overwritten
2
- import 'bson';
2
+ import 'mongodb';
3
3
 
4
- declare module 'bson' {
4
+ declare module 'mongodb' {
5
5
  interface ObjectId {
6
6
  /** Mongoose automatically adds a conveniency "_id" getter on the base ObjectId class */
7
7
  _id: this;
@@ -11,6 +11,12 @@ declare module 'mongoose' {
11
11
  middleware?: boolean | SkipMiddlewareOptions;
12
12
  }
13
13
 
14
+ interface ValidateSyncOptions extends Omit<ValidateOptions, 'middleware'> {
15
+ /** `validateSync()` does not run middleware. Use `validate()` if you need middleware. */
16
+ middleware?: never;
17
+ [k: string]: any;
18
+ }
19
+
14
20
  interface DocumentSetOptions {
15
21
  merge?: boolean;
16
22
 
@@ -32,7 +38,7 @@ declare module 'mongoose' {
32
38
  _id: T;
33
39
 
34
40
  /** Assert that a given path or paths is populated. Throws an error if not populated. */
35
- $assertPopulated<Paths = {}>(path: string | string[], values?: Partial<Paths>): Omit<this, keyof Paths> & Paths;
41
+ $assertPopulated<Paths = {}>(path: string | string[], values?: Partial<Paths>): PopulateDocumentResult<this, Paths, PopulatedPathsDocumentType<DocType, Paths>, DocType>;
36
42
 
37
43
  /** Clear the document's modified paths. */
38
44
  $clearModifiedPaths(): this;
@@ -171,6 +177,13 @@ declare module 'mongoose' {
171
177
  * Returns the changes that happened to the document
172
178
  * in the format that will be sent to MongoDB.
173
179
  */
180
+ $getChanges(): UpdateQuery<this>;
181
+
182
+ /**
183
+ * Returns the changes that happened to the document
184
+ * in the format that will be sent to MongoDB.
185
+ * @deprecated Use `$getChanges()` instead.
186
+ */
174
187
  getChanges(): UpdateQuery<this>;
175
188
 
176
189
  /** Signal that we desire an increment of this documents version. */
@@ -238,8 +251,8 @@ declare module 'mongoose' {
238
251
  $parent(): Document | undefined;
239
252
 
240
253
  /** Populates document references. */
241
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<MergeType<this, Paths>>;
242
- populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions): Promise<MergeType<this, Paths>>;
254
+ populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<PopulateDocumentResult<this, Paths, PopulatedPathsDocumentType<DocType, Paths>, DocType>>;
255
+ populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions): Promise<PopulateDocumentResult<this, Paths, PopulatedPathsDocumentType<DocType, Paths>, DocType>>;
243
256
 
244
257
  /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
245
258
  populated(path: string): any;
@@ -262,11 +275,41 @@ declare module 'mongoose' {
262
275
  toBSON(): Require_id<DocType>;
263
276
 
264
277
  /** The return value of this method is used in calls to JSON.stringify(doc). */
278
+ toJSON<PopulatedRawDocType, DepopulatedRawDocType>(
279
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
280
+ options: { depopulate: true }
281
+ ): Default__v<Require_id<DepopulatedRawDocType>, TSchemaOptions>;
282
+ toJSON<PopulatedRawDocType, DepopulatedRawDocType, O extends ToObjectOptions & { depopulate: true }>(
283
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
284
+ options: O
285
+ ): ToObjectReturnType<DepopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
286
+ toJSON<PopulatedRawDocType, O extends ToObjectOptions>(
287
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>,
288
+ options: O
289
+ ): ToObjectReturnType<PopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
290
+ toJSON<PopulatedRawDocType>(
291
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>
292
+ ): Default__v<Require_id<PopulatedRawDocType>, TSchemaOptions>;
265
293
  toJSON<O extends ToObjectOptions>(options: O): ToObjectReturnType<DocType, TVirtuals, O, TSchemaOptions>;
266
294
  toJSON(options?: ToObjectOptions): Default__v<Require_id<DocType>, TSchemaOptions>;
267
295
  toJSON<T>(options?: ToObjectOptions): Default__v<Require_id<T>, ResolveSchemaOptions<TSchemaOptions>>;
268
296
 
269
297
  /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
298
+ toObject<PopulatedRawDocType, DepopulatedRawDocType>(
299
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
300
+ options: { depopulate: true }
301
+ ): Default__v<Require_id<DepopulatedRawDocType>, TSchemaOptions>;
302
+ toObject<PopulatedRawDocType, DepopulatedRawDocType, O extends ToObjectOptions & { depopulate: true }>(
303
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
304
+ options: O
305
+ ): ToObjectReturnType<DepopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
306
+ toObject<PopulatedRawDocType, O extends ToObjectOptions>(
307
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>,
308
+ options: O
309
+ ): ToObjectReturnType<PopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
310
+ toObject<PopulatedRawDocType>(
311
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>
312
+ ): Default__v<Require_id<PopulatedRawDocType>, TSchemaOptions>;
270
313
  toObject<O extends ToObjectOptions>(options: O): ToObjectReturnType<DocType, TVirtuals, O, TSchemaOptions>;
271
314
  toObject(options?: ToObjectOptions): Default__v<Require_id<DocType>, TSchemaOptions>;
272
315
  toObject<T>(options?: ToObjectOptions): Default__v<Require_id<T>, ResolveSchemaOptions<TSchemaOptions>>;
@@ -283,9 +326,20 @@ declare module 'mongoose' {
283
326
  validate(pathsToValidate?: pathsToValidate, options?: Omit<ValidateOptions, 'pathsToSkip'> & AnyObject): Promise<void>;
284
327
  validate(options: ValidateOptions): Promise<void>;
285
328
 
286
- /** Executes registered validation rules (skipping asynchronous validators) for this document. */
287
- validateSync(options: ValidateOptions & { [k: string]: any }): Error.ValidationError | null;
288
- validateSync<T extends keyof DocType>(pathsToValidate?: T | T[], options?: Omit<ValidateOptions, 'pathsToSkip'> & AnyObject): Error.ValidationError | null;
289
- validateSync(pathsToValidate?: pathsToValidate, options?: Omit<ValidateOptions, 'pathsToSkip'> & AnyObject): Error.ValidationError | null;
329
+ /**
330
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
331
+ * @deprecated Use `validate()` instead. `validateSync()` does not run middleware and will be removed in Mongoose 10.
332
+ */
333
+ validateSync(options: ValidateSyncOptions): Error.ValidationError | null;
334
+ /**
335
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
336
+ * @deprecated Use `validate()` instead. `validateSync()` does not run middleware and will be removed in Mongoose 10.
337
+ */
338
+ validateSync<T extends keyof DocType>(pathsToValidate?: T | T[], options?: Omit<ValidateSyncOptions, 'pathsToSkip'>): Error.ValidationError | null;
339
+ /**
340
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
341
+ * @deprecated Use `validate()` instead. `validateSync()` does not run middleware and will be removed in Mongoose 10.
342
+ */
343
+ validateSync(pathsToValidate?: pathsToValidate, options?: Omit<ValidateSyncOptions, 'pathsToSkip'>): Error.ValidationError | null;
290
344
  }
291
345
  }
@@ -2313,6 +2313,19 @@ declare module 'mongoose' {
2313
2313
  }
2314
2314
  }
2315
2315
 
2316
+ export interface Percentile {
2317
+ /**
2318
+ * Returns an array of scalar values that correspond to specified percentile values.
2319
+ *
2320
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/percentile/
2321
+ */
2322
+ $percentile: {
2323
+ input: number | Expression,
2324
+ p: (number | Expression)[],
2325
+ method: 'approximate'
2326
+ }
2327
+ }
2328
+
2316
2329
  export interface StdDevPop {
2317
2330
  /**
2318
2331
  * Calculates the population standard deviation of the input values. Use if the values encompass the entire
@@ -2874,6 +2887,7 @@ declare module 'mongoose' {
2874
2887
  Expression.Median |
2875
2888
  Expression.Min |
2876
2889
  Expression.MinN |
2890
+ Expression.Percentile |
2877
2891
  Expression.Push |
2878
2892
  Expression.Rank |
2879
2893
  Expression.Shift |
@@ -2906,6 +2920,7 @@ declare module 'mongoose' {
2906
2920
  Expression.Max |
2907
2921
  Expression.Median |
2908
2922
  Expression.Min |
2923
+ Expression.Percentile |
2909
2924
  Expression.StdDevPop |
2910
2925
  Expression.StdDevSamp |
2911
2926
  Expression.Sum;
@@ -2981,6 +2996,7 @@ declare module 'mongoose' {
2981
2996
  Expression.MergeObjects |
2982
2997
  Expression.Min |
2983
2998
  Expression.MinN |
2999
+ Expression.Percentile |
2984
3000
  Expression.Push |
2985
3001
  Expression.StdDevPop |
2986
3002
  Expression.StdDevSamp |
package/types/index.d.ts CHANGED
@@ -24,6 +24,7 @@
24
24
  /// <reference path="./inferrawdoctype.d.ts" />
25
25
  /// <reference path="./inferschematype.d.ts" />
26
26
  /// <reference path="./virtuals.d.ts" />
27
+ /// <reference path="./tracing.d.ts" />
27
28
  /// <reference path="./augmentations.d.ts" />
28
29
 
29
30
  declare class NativeDate extends globalThis.Date { }
@@ -177,13 +178,27 @@ declare module 'mongoose' {
177
178
  HydratedDocPathsType,
178
179
  any,
179
180
  TOverrides extends Record<string, never> ?
180
- Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> & Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions> & AddDefaultId<HydratedDocPathsType, {}, TSchemaOptions> :
181
+ Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> &
182
+ Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions> &
183
+ IfEquals<
184
+ TVirtuals,
185
+ {},
186
+ AddDefaultId<HydratedDocPathsType, {}, TSchemaOptions>,
187
+ TVirtuals
188
+ > :
181
189
  IfAny<
182
190
  TOverrides,
183
191
  Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> & Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions>,
184
192
  Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> & MergeType<
185
193
  Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions>,
186
- TOverrides
194
+ HydratedDocumentOverrides<
195
+ IfEquals<
196
+ TOverrides,
197
+ {},
198
+ TOverrides,
199
+ TOverrides & AddDefaultId<HydratedDocPathsType, TVirtuals, TSchemaOptions>
200
+ >
201
+ >
187
202
  >
188
203
  >
189
204
  >;
@@ -807,12 +822,12 @@ declare module 'mongoose' {
807
822
 
808
823
  export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
809
824
 
810
- type ArrayOperators = { $slice: number | [number, number]; $elemMatch?: never } | { $elemMatch: Record<string, any>; $slice?: never };
825
+ export type ArrayProjectionOperators = { $slice: number | [number, number]; $elemMatch?: never } | { $elemMatch: Record<string, any>; $slice?: never };
811
826
  /**
812
827
  * This Type Assigns `Element | undefined` recursively to the `T` type.
813
828
  * if it is an array it will do this to the element of the array, if it is an object it will do this for the properties of the object.
814
829
  * `Element` is the truthy or falsy values that are going to be used as the value of the projection.(1 | true or 0 | false)
815
- * For the elements of the array we will use: `Element | `undefined` | `ArrayOperators`
830
+ * For the elements of the array we will use: `Element | `undefined` | `ArrayProjectionOperators`
816
831
  * @example
817
832
  * type CalculatedType = Projector<{ a: string, b: number, c: { d: string }, d: string[] }, true>
818
833
  * type CalculatedType = {
@@ -821,11 +836,11 @@ declare module 'mongoose' {
821
836
  c?: true | {
822
837
  d?: true | undefined;
823
838
  } | undefined;
824
- d?: true | ArrayOperators | undefined;
839
+ d?: true | ArrayProjectionOperators | undefined;
825
840
  }
826
841
  */
827
- type Projector<T, Element> = T extends Array<infer U>
828
- ? Projector<U, Element> | ArrayOperators
842
+ export type Projector<T, Element> = T extends Array<infer U>
843
+ ? Projector<U, Element> | ArrayProjectionOperators
829
844
  : T extends TreatAsPrimitives
830
845
  ? Element
831
846
  : T extends Record<string, any>
@@ -1094,6 +1109,9 @@ declare module 'mongoose' {
1094
1109
  // Handle DocumentArray - recurse into items
1095
1110
  : T extends Types.DocumentArray<infer ItemType>
1096
1111
  ? Types.DocumentArray<ApplyFlattenTransforms<ItemType, O>>
1112
+ // Handle plain arrays - recurse into items
1113
+ : T extends Array<infer ItemType>
1114
+ ? ApplyFlattenTransforms<ItemType, O>[]
1097
1115
  // Handle Subdocument - recurse into subdoc type
1098
1116
  : T extends Types.Subdocument<unknown, unknown, infer SubdocType>
1099
1117
  ? HydratedSingleSubdocument<ApplyFlattenTransforms<SubdocType, O>>
@@ -104,7 +104,7 @@ declare module 'mongoose' {
104
104
  Types.Subdocument<InferHydratedDocType<Item>['_id'], unknown, InferHydratedDocType<Item>> & InferHydratedDocType<Item>
105
105
  >:
106
106
  IsSchemaTypeFromBuiltinClass<Item> extends true ?
107
- Types.Array<ResolveHydratedPathType<Item, { enum: Options['enum'] }, TypeKey>> :
107
+ Types.Array<ResolveHydratedPathType<Item, { enum: Exclude<Options['enum'], undefined> }, TypeKey>> :
108
108
  IsItRecordAndNotAny<Item> extends true ?
109
109
  Item extends Record<string, never> ?
110
110
  Types.Array<ObtainHydratedDocumentPathType<Item, TypeKey>> :
@@ -3,7 +3,8 @@ import {
3
3
  PathEnumOrString,
4
4
  OptionalPaths,
5
5
  RequiredPaths,
6
- IsPathRequired
6
+ IsPathRequired,
7
+ PathAllowsNull
7
8
  } from './inferschematype';
8
9
  import { Binary, UUID } from 'mongodb';
9
10
 
@@ -24,7 +25,9 @@ declare module 'mongoose' {
24
25
  OptionalPaths<SchemaDefinition, TSchemaOptions['typeKey']>)
25
26
  ]: IsPathRequired<SchemaDefinition[K], TSchemaOptions['typeKey']> extends true
26
27
  ? ObtainRawDocumentPathType<SchemaDefinition[K], TSchemaOptions['typeKey'], TTransformOptions>
27
- : ObtainRawDocumentPathType<SchemaDefinition[K], TSchemaOptions['typeKey'], TTransformOptions> | null;
28
+ : PathAllowsNull<SchemaDefinition[K]> extends true
29
+ ? ObtainRawDocumentPathType<SchemaDefinition[K], TSchemaOptions['typeKey'], TTransformOptions> | null
30
+ : ObtainRawDocumentPathType<SchemaDefinition[K], TSchemaOptions['typeKey'], TTransformOptions>;
28
31
  }, TSchemaOptions>;
29
32
 
30
33
  export type InferRawDocType<
@@ -141,7 +144,7 @@ declare module 'mongoose' {
141
144
  : // If the type key isn't callable, then this is an array of objects, in which case
142
145
  // we need to call InferRawDocType to correctly infer its type.
143
146
  Array<InferRawDocType<Item, DefaultSchemaOptions, TTransformOptions>>
144
- : IsSchemaTypeFromBuiltinClass<Item> extends true ? ResolveRawPathType<Item, { enum: Options['enum'] }, TypeKey, TTransformOptions>[]
147
+ : IsSchemaTypeFromBuiltinClass<Item> extends true ? ResolveRawPathType<Item, { enum: Exclude<Options['enum'], undefined> }, TypeKey, TTransformOptions>[]
145
148
  : IsItRecordAndNotAny<Item> extends true ?
146
149
  Item extends Record<string, never> ?
147
150
  ObtainRawDocumentPathType<Item, TypeKey, TTransformOptions>[]
@@ -47,7 +47,9 @@ declare module 'mongoose' {
47
47
  TSchemaOptions['typeKey']
48
48
  > extends true ?
49
49
  ObtainDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']>
50
- : ObtainDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']> | null;
50
+ : PathAllowsNull<DocDefinition[K]> extends true ?
51
+ ObtainDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']> | null
52
+ : ObtainDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']>;
51
53
  };
52
54
 
53
55
  /**
@@ -222,6 +224,12 @@ type OptionalPaths<T, TypeKey extends string = DefaultTypeKey> = Pick<
222
224
  OptionalPathKeys<T, TypeKey>
223
225
  >;
224
226
 
227
+ /**
228
+ * @summary Checks if a document path allows `null` values.
229
+ * @param {P} P Document path.
230
+ */
231
+ export type PathAllowsNull<P> = P extends { allowNull: false } ? false : true;
232
+
225
233
  /**
226
234
  * @summary Allows users to optionally choose their own type for a schema field for stronger typing.
227
235
  */
@@ -337,7 +345,7 @@ type ResolvePathType<
337
345
  : // If the type key isn't callable, then this is an array of objects, in which case
338
346
  // we need to call ObtainDocumentType to correctly infer its type.
339
347
  Types.DocumentArray<ObtainDocumentType<Item, any, { typeKey: TypeKey }>>
340
- : IsSchemaTypeFromBuiltinClass<Item> extends true ? ResolvePathType<Item, { enum: Options['enum'] }, TypeKey>[]
348
+ : IsSchemaTypeFromBuiltinClass<Item> extends true ? ResolvePathType<Item, { enum: Exclude<Options['enum'], undefined> }, TypeKey>[]
341
349
  : IsItRecordAndNotAny<Item> extends true ?
342
350
  Item extends Record<string, never> ?
343
351
  ObtainDocumentPathType<Item, TypeKey>[]
package/types/models.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  declare module 'mongoose' {
2
2
  import mongodb = require('mongodb');
3
+ import { StandardSchemaV1 as StandardSchemaV1Spec, StandardTypedV1 as StandardTypedV1Spec } from '@standard-schema/spec';
3
4
 
4
5
  export interface DiscriminatorOptions {
5
6
  value?: string | number | ObjectId;
@@ -108,10 +109,15 @@ declare module 'mongoose' {
108
109
  */
109
110
  type pathsToValidate = PathsToValidate;
110
111
 
112
+ export import StandardTypedV1 = StandardTypedV1Spec;
113
+ export import StandardSchemaV1 = StandardSchemaV1Spec;
114
+
111
115
  interface SaveOptions extends
112
116
  SessionOption {
113
117
  checkKeys?: boolean;
114
118
  j?: boolean;
119
+ /** An array of paths that tell mongoose to only validate and save the paths in `pathsToSave`. */
120
+ pathsToSave?: string[];
115
121
  safe?: boolean | WriteConcern;
116
122
  timestamps?: boolean | QueryTimestampsConfig;
117
123
  validateBeforeSave?: boolean;
@@ -189,18 +195,18 @@ declare module 'mongoose' {
189
195
  * - vanilla arrays of POJOs for document arrays
190
196
  * - POJOs and array of arrays for maps
191
197
  */
192
- type CreateObjectWithExtraKeys<T> = T & Record<string, unknown>;
198
+ type CreateObjectWithExtraKeys<T> = T | (T & Record<string, unknown>);
193
199
  type ApplyBasicCreateCasting<T> = {
194
200
  [K in keyof T]: NonNullable<T[K]> extends Map<infer KeyType extends string, infer ValueType>
195
- ? (Record<KeyType, ValueType> | Array<[KeyType, ValueType]> | T[K])
201
+ ? (Record<KeyType, ValueType> | Array<[KeyType, ValueType]> | T[K] | QueryTypeCasting<Extract<T[K], TreatAsPrimitives>>)
196
202
  : NonNullable<T[K]> extends Types.DocumentArray<infer RawSubdocType>
197
- ? RawSubdocType[] | T[K]
203
+ ? RawSubdocType[] | T[K] | QueryTypeCasting<Extract<T[K], TreatAsPrimitives>>
198
204
  : NonNullable<T[K]> extends Document<any, any, infer RawSubdocType>
199
- ? CreateObjectWithExtraKeys<ApplyBasicCreateCasting<RawSubdocType>> | T[K]
205
+ ? CreateObjectWithExtraKeys<ApplyBasicCreateCasting<RawSubdocType>> | T[K] | QueryTypeCasting<Extract<T[K], TreatAsPrimitives>>
200
206
  : NonNullable<T[K]> extends TreatAsPrimitives
201
207
  ? QueryTypeCasting<T[K]>
202
208
  : NonNullable<T[K]> extends object
203
- ? CreateObjectWithExtraKeys<ApplyBasicCreateCasting<T[K]>> | T[K]
209
+ ? CreateObjectWithExtraKeys<ApplyBasicCreateCasting<T[K]>> | T[K] | QueryTypeCasting<Extract<T[K], TreatAsPrimitives>>
204
210
  : QueryTypeCasting<T[K]>;
205
211
  };
206
212
 
@@ -234,6 +240,9 @@ declare module 'mongoose' {
234
240
  /** Base Mongoose instance the model uses. */
235
241
  base: Mongoose;
236
242
 
243
+ /** Standard Schema adapter for validating input with this model's schema. */
244
+ readonly '~standard': StandardSchemaV1.Props<Default__v<Require_id<TRawDocType>, ObtainSchemaGeneric<TSchema, 'TSchemaOptions'>>>;
245
+
237
246
  /**
238
247
  * If this is a discriminator model, `baseModelName` is the name of
239
248
  * the base model.
@@ -509,8 +518,16 @@ declare module 'mongoose' {
509
518
  /**
510
519
  * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
511
520
  * The document returned has no paths marked as modified initially.
521
+ * With `strict: false`, fields not in the schema are kept on the document; pass
522
+ * `ExtraFields` to describe their types, e.g.
523
+ * `Model.hydrate<{ totalOrders: number }>(obj, null, { strict: false })`.
512
524
  */
513
- hydrate(obj: any, projection?: ProjectionType<TRawDocType>, options?: HydrateOptions): THydratedDocumentType;
525
+ hydrate<ExtraFields = unknown>(
526
+ obj: any,
527
+ projection: ProjectionType<TRawDocType> | null | undefined,
528
+ options: HydrateOptions & { strict: false }
529
+ ): THydratedDocumentType & ExtraFields;
530
+ hydrate(obj: any, projection?: ProjectionType<TRawDocType> | null | undefined, options?: HydrateOptions): THydratedDocumentType;
514
531
 
515
532
  /**
516
533
  * This function is responsible for building [indexes](https://www.mongodb.com/docs/manual/indexes/),
@@ -628,10 +645,10 @@ declare module 'mongoose' {
628
645
  populate<Paths>(
629
646
  docs: Array<any>,
630
647
  options: PopulateOptions | Array<PopulateOptions> | string
631
- ): Promise<Array<MergeType<THydratedDocumentType, Paths>>>;
648
+ ): Promise<Array<PopulateDocumentResult<THydratedDocumentType, Paths, PopulatedPathsDocumentType<TRawDocType, Paths>, TRawDocType>>>;
632
649
  populate<Paths>(
633
650
  doc: any, options: PopulateOptions | Array<PopulateOptions> | string
634
- ): Promise<MergeType<THydratedDocumentType, Paths>>;
651
+ ): Promise<PopulateDocumentResult<THydratedDocumentType, Paths, PopulatedPathsDocumentType<TRawDocType, Paths>, TRawDocType>>;
635
652
 
636
653
  /**
637
654
  * Update an existing [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/).
@@ -646,11 +663,11 @@ declare module 'mongoose' {
646
663
  */
647
664
  useConnection(connection: Connection): this;
648
665
 
649
- /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
650
- validate(): Promise<void>;
651
- validate(obj: any): Promise<void>;
652
- validate(obj: any, pathsOrOptions: PathsToValidate): Promise<void>;
653
- validate(obj: any, pathsOrOptions: { pathsToSkip?: pathsToSkip }): Promise<void>;
666
+ /** Casts and validates the given object against this model's schema, returning the casted-and-validated copy of `obj`, passing the given `context` to custom validators. */
667
+ validate(): Promise<TRawDocType>;
668
+ validate(obj: any): Promise<TRawDocType>;
669
+ validate(obj: any, pathsOrOptions: PathsToValidate): Promise<TRawDocType>;
670
+ validate(obj: any, pathsOrOptions: { pathsToSkip?: pathsToSkip }): Promise<TRawDocType>;
654
671
 
655
672
  /** Watches the underlying collection for changes using [MongoDB change streams](https://www.mongodb.com/docs/manual/changeStreams/). */
656
673
  watch<ResultType extends mongodb.Document = any, ChangeType extends mongodb.ChangeStreamDocument = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions & { hydrate?: boolean }): mongodb.ChangeStream<ResultType, ChangeType>;
@@ -82,7 +82,7 @@ declare module 'mongoose' {
82
82
  */
83
83
  debug?:
84
84
  | boolean
85
- | { color?: boolean; shell?: boolean; }
85
+ | { color?: boolean; shell?: boolean; timestamp?: boolean; }
86
86
  | stream.Writable
87
87
  | ((collectionName: string, methodName: string, ...methodArgs: any[]) => void);
88
88
 
@@ -192,6 +192,14 @@ declare module 'mongoose' {
192
192
  */
193
193
  strictQuery?: boolean | 'throw';
194
194
 
195
+ /**
196
+ * Sets the default [strictRead](https://mongoosejs.com/docs/guide.html#strictRead) mode for schemas.
197
+ * May be `false`, `true`, or `'throw'`.
198
+ *
199
+ * @default false
200
+ */
201
+ strictRead?: boolean | 'throw';
202
+
195
203
  /**
196
204
  * Overwrites default objects to `toJSON()`, for determining how Mongoose
197
205
  * documents get serialized by `JSON.stringify()`