@datanimbus/mongoose 6.13.13 → 9.13.2

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 (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
@@ -9,17 +9,12 @@ declare module 'mongoose' {
9
9
  const connections: Connection[];
10
10
 
11
11
  /** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
12
- function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
13
- function connect(uri: string, callback: CallbackWithoutResult): void;
14
12
  function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
15
13
 
16
14
  /** Creates a Connection instance. */
17
- function createConnection(uri: string, options: ConnectOptions, callback: Callback<Connection>): void;
18
- function createConnection(uri: string, callback: Callback<Connection>): void;
19
15
  function createConnection(uri: string, options?: ConnectOptions): Connection;
20
16
  function createConnection(): Connection;
21
17
 
22
- function disconnect(callback: CallbackWithoutResult): void;
23
18
  function disconnect(): Promise<void>;
24
19
 
25
20
  /**
@@ -53,22 +48,52 @@ declare module 'mongoose' {
53
48
  pass?: string;
54
49
  /** Set to false to disable automatic index creation for all models associated with this connection. */
55
50
  autoIndex?: boolean;
56
- /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
51
+ /** Set to `false` to disable Mongoose automatically calling `createCollection()` on every model created on this connection. */
57
52
  autoCreate?: boolean;
53
+ /**
54
+ * Sanitizes query filters against [query selector injection attacks](
55
+ * https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html
56
+ * ) by wrapping any nested objects that have a property whose name starts with $ in a $eq.
57
+ */
58
+ sanitizeFilter?: boolean;
58
59
  }
59
60
 
61
+ export type AnyConnectionBulkWriteModel<TSchema extends AnyObject> = Omit<mongodb.ClientInsertOneModel<TSchema>, 'namespace'>
62
+ | Omit<mongodb.ClientReplaceOneModel<TSchema>, 'namespace'>
63
+ | Omit<mongodb.ClientUpdateOneModel<TSchema>, 'namespace'>
64
+ | Omit<mongodb.ClientUpdateManyModel<TSchema>, 'namespace'>
65
+ | Omit<mongodb.ClientDeleteOneModel<TSchema>, 'namespace'>
66
+ | Omit<mongodb.ClientDeleteManyModel<TSchema>, 'namespace'>;
67
+
68
+ export type ConnectionBulkWriteModel<SchemaMap extends Record<string, AnyObject> = Record<string, AnyObject>> = {
69
+ [ModelName in keyof SchemaMap]: AnyConnectionBulkWriteModel<SchemaMap[ModelName]> & {
70
+ model: ModelName;
71
+ };
72
+ }[keyof SchemaMap];
73
+
60
74
  class Connection extends events.EventEmitter implements SessionStarter {
75
+ /** Runs a [db-level aggregate()](https://www.mongodb.com/docs/manual/reference/method/db.aggregate/) on this connection's underlying `db` */
76
+ aggregate<ResultType = unknown>(pipeline?: PipelineStage[] | null, options?: AggregateOptions): Aggregate<Array<ResultType>>;
77
+
61
78
  /** Returns a promise that resolves when this connection successfully connects to MongoDB */
62
79
  asPromise(): Promise<this>;
63
80
 
81
+ /** The Mongoose instance this connection is associated with */
82
+ base: Mongoose;
83
+
84
+ bulkWrite<TSchemaMap extends Record<string, AnyObject>>(
85
+ ops: Array<ConnectionBulkWriteModel<TSchemaMap>>,
86
+ options: mongodb.ClientBulkWriteOptions & { ordered: false }
87
+ ): Promise<mongodb.ClientBulkWriteResult & { mongoose?: { validationErrors: Error[], results: Array<Error | mongodb.WriteError | null> } }>;
88
+ bulkWrite<TSchemaMap extends Record<string, AnyObject>>(
89
+ ops: Array<ConnectionBulkWriteModel<TSchemaMap>>,
90
+ options?: mongodb.ClientBulkWriteOptions
91
+ ): Promise<mongodb.ClientBulkWriteResult>;
92
+
64
93
  /** Closes the connection */
65
- close(force: boolean, callback: CallbackWithoutResult): void;
66
- close(callback: CallbackWithoutResult): void;
67
94
  close(force?: boolean): Promise<void>;
68
95
 
69
96
  /** Closes and destroys the connection. Connection once destroyed cannot be reopened */
70
- destroy(force: boolean, callback: CallbackWithoutResult): void;
71
- destroy(callback: CallbackWithoutResult): void;
72
97
  destroy(force?: boolean): Promise<void>;
73
98
 
74
99
  /** Retrieves a collection, creating it if not cached. */
@@ -81,17 +106,20 @@ declare module 'mongoose' {
81
106
  readonly config: any;
82
107
 
83
108
  /** The mongodb.Db instance, set when the connection is opened */
84
- readonly db: mongodb.Db;
109
+ readonly db: mongodb.Db | undefined;
85
110
 
86
111
  /**
87
112
  * Helper for `createCollection()`. Will explicitly create the given collection
88
113
  * with specified options. Used to create [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections/)
89
114
  * and [views](https://www.mongodb.com/docs/manual/core/views/) from mongoose.
90
115
  */
91
- createCollection<T extends AnyObject = AnyObject>(name: string, options: mongodb.CreateCollectionOptions, callback: Callback<mongodb.Collection<T>>): void;
92
- createCollection<T extends AnyObject = AnyObject>(name: string, callback: Callback<mongodb.Collection<T>>): void;
93
116
  createCollection<T extends AnyObject = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Promise<mongodb.Collection<T>>;
94
117
 
118
+ /**
119
+ * https://mongoosejs.com/docs/api/connection.html#Connection.prototype.createCollections()
120
+ */
121
+ createCollections(continueOnError?: boolean): Promise<Record<string, Error | mongodb.Collection<any>>>;
122
+
95
123
  /**
96
124
  * Removes the model named `name` from this connection, if it exists. You can
97
125
  * use this function to clean up any models you created in your tests to
@@ -103,21 +131,19 @@ declare module 'mongoose' {
103
131
  * Helper for `dropCollection()`. Will delete the given collection, including
104
132
  * all documents and indexes.
105
133
  */
106
- dropCollection(collection: string, callback: CallbackWithoutResult): void;
107
134
  dropCollection(collection: string): Promise<void>;
108
135
 
109
136
  /**
110
137
  * Helper for `dropDatabase()`. Deletes the given database, including all
111
138
  * collections, documents, and indexes.
112
139
  */
113
- dropDatabase(callback: CallbackWithoutResult): void;
114
140
  dropDatabase(): Promise<void>;
115
141
 
116
142
  /** Gets the value of the option `key`. */
117
143
  get(key: string): any;
118
144
 
119
145
  /**
120
- * Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html) instance
146
+ * Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html) instance
121
147
  * that this connection uses to talk to MongoDB.
122
148
  */
123
149
  getClient(): mongodb.MongoClient;
@@ -134,6 +160,18 @@ declare module 'mongoose' {
134
160
  */
135
161
  readonly id: number;
136
162
 
163
+ /**
164
+ * Helper for MongoDB Node driver's `listCollections()`.
165
+ * Returns an array of collection names.
166
+ */
167
+ listCollections(): Promise<Pick<mongodb.CollectionInfo, 'name' | 'type'>[]>;
168
+
169
+ /**
170
+ * Helper for MongoDB Node driver's `listDatabases()`.
171
+ * Returns an array of database names.
172
+ */
173
+ listDatabases(): Promise<mongodb.ListDatabasesResult>;
174
+
137
175
  /**
138
176
  * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
139
177
  * a map from model names to models. Contains all models that have been
@@ -147,14 +185,33 @@ declare module 'mongoose' {
147
185
  schema?: TSchema,
148
186
  collection?: string,
149
187
  options?: CompileModelOptions
150
- ): Model<InferSchemaType<TSchema>, ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>, ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>, {}, TSchema> & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
188
+ ): Model<
189
+ InferSchemaType<TSchema>,
190
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
191
+ ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
192
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
193
+ // If first schema generic param is set, that means we have an explicit raw doc type,
194
+ // so user should also specify a hydrated doc type if the auto inferred one isn't correct.
195
+ IsItRecordAndNotAny<ObtainSchemaGeneric<TSchema, 'EnforcedDocType'>> extends true
196
+ ? ObtainSchemaGeneric<TSchema, 'THydratedDocumentType'>
197
+ : HydratedDocument<
198
+ InferSchemaType<TSchema>,
199
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'> & ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
200
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
201
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
202
+ InferSchemaType<TSchema>,
203
+ ObtainSchemaGeneric<TSchema, 'TSchemaOptions'>
204
+ >,
205
+ TSchema,
206
+ Default__v<Require_id<ObtainSchemaGeneric<TSchema, 'TLeanResultType'>>>
207
+ > & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
151
208
  model<T, U, TQueryHelpers = {}>(
152
209
  name: string,
153
- schema?: Schema<T, any, any, TQueryHelpers, any, any>,
210
+ schema?: Schema<T, any, any, TQueryHelpers, any, any, any>,
154
211
  collection?: string,
155
212
  options?: CompileModelOptions
156
213
  ): U;
157
- model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
214
+ model<T>(name: string, schema?: Schema<T, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
158
215
 
159
216
  /** Returns an array of model names created on this connection. */
160
217
  modelNames(): Array<string>;
@@ -163,8 +220,6 @@ declare module 'mongoose' {
163
220
  readonly name: string;
164
221
 
165
222
  /** Opens the connection with a URI using `MongoClient.connect()`. */
166
- openUri(uri: string, options: ConnectOptions, callback: Callback<Connection>): Connection;
167
- openUri(uri: string, callback: Callback<Connection>): Connection;
168
223
  openUri(uri: string, options?: ConnectOptions): Promise<Connection>;
169
224
 
170
225
  /** The password specified in the URI */
@@ -197,7 +252,7 @@ declare module 'mongoose' {
197
252
  set(key: string, value: any): any;
198
253
 
199
254
  /**
200
- * Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html) instance
255
+ * Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html) instance
201
256
  * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
202
257
  * reuse it.
203
258
  */
@@ -208,8 +263,6 @@ declare module 'mongoose' {
208
263
  * for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
209
264
  * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
210
265
  */
211
- startSession(options: ClientSessionOptions | undefined | null, callback: Callback<ClientSession>): void;
212
- startSession(callback: Callback<ClientSession>): void;
213
266
  startSession(options?: ClientSessionOptions): Promise<ClientSession>;
214
267
 
215
268
  /**
@@ -218,7 +271,6 @@ declare module 'mongoose' {
218
271
  * the model's schema except the `_id` index, and build any indexes that
219
272
  * are in your schema but not in MongoDB.
220
273
  */
221
- syncIndexes(options: SyncIndexesOptions | undefined | null, callback: Callback<ConnectionSyncIndexesResult>): void;
222
274
  syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
223
275
 
224
276
  /**
@@ -227,16 +279,19 @@ declare module 'mongoose' {
227
279
  * async function executes successfully and attempt to retry if
228
280
  * there was a retryable error.
229
281
  */
230
- transaction(fn: (session: mongodb.ClientSession) => Promise<any>, options?: mongodb.TransactionOptions): Promise<void>;
282
+ transaction<ReturnType = unknown>(fn: (session: mongodb.ClientSession) => Promise<ReturnType>, options?: mongodb.TransactionOptions): Promise<ReturnType>;
231
283
 
232
284
  /** Switches to a different database using the same connection pool. */
233
- useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
285
+ useDb(name: string, options?: { useCache?: boolean }): Connection;
234
286
 
235
287
  /** The username specified in the URI */
236
288
  readonly user: string;
237
289
 
238
290
  /** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model-watch). */
239
291
  watch<ResultType extends mongodb.Document = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
292
+
293
+ withSession<T = any>(executor: (session: ClientSession) => Promise<T>): Promise<T>;
240
294
  }
241
295
 
296
+ export class BaseConnection extends Connection {}
242
297
  }
package/types/cursor.d.ts CHANGED
@@ -8,13 +8,16 @@ declare module 'mongoose' {
8
8
  parallel?: number;
9
9
  batchSize?: number;
10
10
  continueOnError?: boolean;
11
+ signal?: AbortSignal;
11
12
  }
12
13
 
13
- class Cursor<DocType = any, Options = never> extends stream.Readable {
14
- [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
14
+ class Cursor<DocType = any, Options = never, NextResultType = DocType | null> extends stream.Readable {
15
+ [Symbol.asyncIterator](): Cursor<IteratorResult<DocType>, Options, IteratorResult<DocType>>;
16
+
17
+ [Symbol.asyncDispose](): Promise<void>;
15
18
 
16
19
  /**
17
- * Adds a [cursor flag](https://mongodb.github.io/node-mongodb-native/4.9/classes/FindCursor.html#addCursorFlag).
20
+ * Adds a [cursor flag](https://mongodb.github.io/node-mongodb-native/7.0/classes/FindCursor.html#addCursorFlag).
18
21
  * Useful for setting the `noCursorTimeout` and `tailable` flags.
19
22
  */
20
23
  addCursorFlag(flag: CursorFlag, value: boolean): this;
@@ -23,9 +26,14 @@ declare module 'mongoose' {
23
26
  * Marks this cursor as closed. Will stop streaming and subsequent calls to
24
27
  * `next()` will error.
25
28
  */
26
- close(callback: CallbackWithoutResult): void;
27
29
  close(): Promise<void>;
28
30
 
31
+ /**
32
+ * Destroy this cursor, closing the underlying cursor. Will stop streaming
33
+ * and subsequent calls to `next()` will error.
34
+ */
35
+ destroy(): this;
36
+
29
37
  /**
30
38
  * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
31
39
  * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
@@ -39,10 +47,8 @@ declare module 'mongoose' {
39
47
  * will wait for the promise to resolve before iterating on to the next one.
40
48
  * Returns a promise that resolves when done.
41
49
  */
42
- eachAsync(fn: (doc: DocType[], index: number) => any, options: EachAsyncOptions & { batchSize: number }, callback: CallbackWithoutResult): void;
43
- eachAsync(fn: (doc: DocType, index: number) => any, options: EachAsyncOptions, callback: CallbackWithoutResult): void;
44
- eachAsync(fn: (doc: DocType[], index: number) => any, options: EachAsyncOptions & { batchSize: number }): Promise<void>;
45
- eachAsync(fn: (doc: DocType, index: number) => any, options?: EachAsyncOptions): Promise<void>;
50
+ eachAsync(fn: (doc: DocType[], i: number) => any, options: EachAsyncOptions & { batchSize: number }): Promise<void>;
51
+ eachAsync(fn: (doc: DocType, i: number) => any, options?: EachAsyncOptions): Promise<void>;
46
52
 
47
53
  /**
48
54
  * Registers a transform function which subsequently maps documents retrieved
@@ -54,8 +60,7 @@ declare module 'mongoose' {
54
60
  * Get the next document from this cursor. Will return `null` when there are
55
61
  * no documents left.
56
62
  */
57
- next(callback: Callback<DocType | null>): void;
58
- next(): Promise<DocType>;
63
+ next(): Promise<NextResultType>;
59
64
 
60
65
  options: Options;
61
66
  }
@@ -4,41 +4,62 @@ declare module 'mongoose' {
4
4
  /** A list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. */
5
5
  type pathsToSkip = string[] | string;
6
6
 
7
+ interface ValidateOptions {
8
+ /** List of paths to skip. If set, Mongoose will validate every modified path that is not in this list. */
9
+ pathsToSkip?: pathsToSkip;
10
+ /** set to `false` to skip all user-defined middleware, or `{ pre: false }` / `{ post: false }` to skip only pre or post hooks */
11
+ middleware?: boolean | SkipMiddlewareOptions;
12
+ }
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
+
7
20
  interface DocumentSetOptions {
8
21
  merge?: boolean;
9
22
 
10
23
  [key: string]: any;
11
24
  }
12
25
 
26
+ class ModifiedPathsSnapshot {}
27
+
13
28
  /**
14
29
  * Generic types for Document:
15
30
  * * T - the type of _id
16
31
  * * TQueryHelpers - Object with any helpers that should be mixed into the Query type
17
32
  * * DocType - the type of the actual Document created
18
33
  */
19
- class Document<T = any, TQueryHelpers = any, DocType = any> {
34
+ class Document<T = Types.ObjectId, TQueryHelpers = any, DocType = any, TVirtuals = Record<string, any>, TSchemaOptions = {}> {
20
35
  constructor(doc?: any);
21
36
 
22
37
  /** This documents _id. */
23
- _id?: T;
24
-
25
- /** This documents __v. */
26
- __v?: any;
38
+ _id: T;
27
39
 
28
40
  /** Assert that a given path or paths is populated. Throws an error if not populated. */
29
- $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>;
42
+
43
+ /** Clear the document's modified paths. */
44
+ $clearModifiedPaths(): this;
30
45
 
31
46
  /** Returns a deep clone of this document */
32
47
  $clone(): this;
33
48
 
49
+ /**
50
+ * Creates a snapshot of this document's internal change tracking state. You can later
51
+ * reset this document's change tracking state using `$restoreModifiedPathsSnapshot()`.
52
+ */
53
+ $createModifiedPathsSnapshot(): ModifiedPathsSnapshot;
54
+
34
55
  /* Get all subdocs (by bfs) */
35
56
  $getAllSubdocs(): Document[];
36
57
 
37
58
  /** Don't run validation on this path or persist changes to this path. */
38
59
  $ignore(path: string): void;
39
60
 
40
- /** Checks if a path is set to its default. */
41
- $isDefault(path: string): boolean;
61
+ /** Checks if a path is set to its default. If no path set, checks if any path is set to its default. */
62
+ $isDefault(path?: string): boolean;
42
63
 
43
64
  /** Getter/setter, determines whether the document was removed or not. */
44
65
  $isDeleted(val?: boolean): boolean;
@@ -74,7 +95,8 @@ declare module 'mongoose' {
74
95
  $markValid(path: string): void;
75
96
 
76
97
  /** Returns the model with the given name on this document's associated connection. */
77
- $model<ModelType = Model<unknown>>(name: string): ModelType;
98
+ $model<ModelType extends Model<unknown>>(name: string): ModelType;
99
+ $model<ModelType extends Model<DocType, any, any, any>>(): ModelType;
78
100
 
79
101
  /**
80
102
  * A string containing the current operation that Mongoose is executing
@@ -82,6 +104,13 @@ declare module 'mongoose' {
82
104
  */
83
105
  $op: 'save' | 'validate' | 'remove' | null;
84
106
 
107
+ /**
108
+ * Restore this document's change tracking state to the given snapshot.
109
+ * Note that `$restoreModifiedPathsSnapshot()` does **not** modify the document's
110
+ * properties, just resets the change tracking state.
111
+ */
112
+ $restoreModifiedPathsSnapshot(snapshot: ModifiedPathsSnapshot): this;
113
+
85
114
  /**
86
115
  * Getter/setter around the session associated with this document. Used to
87
116
  * automatically set `session` if you `save()` a doc that you got from a
@@ -90,9 +119,9 @@ declare module 'mongoose' {
90
119
  $session(session?: ClientSession | null): ClientSession | null;
91
120
 
92
121
  /** Alias for `set()`, used internally to avoid conflicts */
93
- $set(path: string, val: any, type: any, options?: DocumentSetOptions): this;
94
- $set(path: string, val: any, options?: DocumentSetOptions): this;
95
- $set(value: any): this;
122
+ $set(path: string | Record<string, any>, val: any, type: any, options?: DocumentSetOptions): this;
123
+ $set(path: string | Record<string, any>, val: any, options?: DocumentSetOptions): this;
124
+ $set(value: string | Record<string, any>): this;
96
125
 
97
126
  /** Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. */
98
127
  $where: Record<string, unknown>;
@@ -107,20 +136,21 @@ declare module 'mongoose' {
107
136
  db: Connection;
108
137
 
109
138
  /** Removes this document from the db. */
110
- delete(options: QueryOptions, callback: Callback): void;
111
- delete(callback: Callback): void;
112
- delete(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
113
-
114
- /** Removes this document from the db. */
115
- deleteOne(options: QueryOptions, callback: Callback): void;
116
- deleteOne(callback: Callback): void;
117
- deleteOne(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
139
+ deleteOne(options?: QueryOptions): QueryWithHelpers<
140
+ mongodb.DeleteResult,
141
+ this,
142
+ TQueryHelpers,
143
+ DocType,
144
+ 'deleteOne',
145
+ Record<string, never>,
146
+ Default__v<Require_id<DocType>>
147
+ >;
118
148
 
119
149
  /**
120
150
  * Takes a populated field and returns it to its unpopulated state. If called with
121
151
  * no arguments, then all populated fields are returned to their unpopulated state.
122
152
  */
123
- depopulate(path?: string | string[]): this;
153
+ depopulate<Paths = {}>(path?: string | string[]): MergeType<this, Paths>;
124
154
 
125
155
  /**
126
156
  * Returns the list of paths that have been directly modified. A direct
@@ -142,16 +172,21 @@ declare module 'mongoose' {
142
172
  errors?: Error.ValidationError;
143
173
 
144
174
  /** Returns the value of a path. */
175
+ get<T extends keyof DocType>(path: T, type?: any, options?: any): DocType[T];
145
176
  get(path: string, type?: any, options?: any): any;
146
177
 
147
178
  /**
148
179
  * Returns the changes that happened to the document
149
180
  * in the format that will be sent to MongoDB.
150
181
  */
151
- getChanges(): UpdateQuery<this>;
182
+ $getChanges(): UpdateQuery<this>;
152
183
 
153
- /** The string version of this documents _id. */
154
- id?: any;
184
+ /**
185
+ * Returns the changes that happened to the document
186
+ * in the format that will be sent to MongoDB.
187
+ * @deprecated Use `$getChanges()` instead.
188
+ */
189
+ getChanges(): UpdateQuery<this>;
155
190
 
156
191
  /** Signal that we desire an increment of this documents version. */
157
192
  increment(): this;
@@ -161,35 +196,46 @@ declare module 'mongoose' {
161
196
  * Called internally after a document is returned from mongodb. Normally,
162
197
  * you do **not** need to call this function on your own.
163
198
  */
164
- init(obj: AnyObject, opts?: AnyObject, callback?: Callback<this>): this;
199
+ init(obj: AnyObject, opts?: AnyObject): this;
165
200
 
166
201
  /** Marks a path as invalid, causing validation to fail. */
202
+ invalidate<T extends keyof DocType>(path: T, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
167
203
  invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
168
204
 
169
205
  /** Returns true if `path` was directly set and modified, else false. */
206
+ isDirectModified<T extends keyof DocType>(path: T | Array<T>): boolean;
170
207
  isDirectModified(path: string | Array<string>): boolean;
171
208
 
172
209
  /** Checks if `path` was explicitly selected. If no projection, always returns true. */
210
+ isDirectSelected<T extends keyof DocType>(path: T): boolean;
173
211
  isDirectSelected(path: string): boolean;
174
212
 
175
213
  /** Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. */
214
+ isInit<T extends keyof DocType>(path: T): boolean;
176
215
  isInit(path: string): boolean;
177
216
 
178
217
  /**
179
218
  * Returns true if any of the given paths are modified, else false. If no arguments, returns `true` if any path
180
219
  * in this document is modified.
181
220
  */
221
+ isModified<T extends keyof DocType>(path?: T | Array<T>, options?: { ignoreAtomics?: boolean } | null): boolean;
182
222
  isModified(path?: string | Array<string>, options?: { ignoreAtomics?: boolean } | null): boolean;
183
223
 
184
224
  /** Boolean flag specifying if the document is new. */
185
225
  isNew: boolean;
186
226
 
187
227
  /** Checks if `path` was selected in the source query which initialized this document. */
228
+ isSelected<T extends keyof DocType>(path: T): boolean;
188
229
  isSelected(path: string): boolean;
189
230
 
190
231
  /** Marks the path as having pending changes to write to the db. */
232
+ markModified<T extends keyof DocType>(path: T, scope?: any): void;
191
233
  markModified(path: string, scope?: any): void;
192
234
 
235
+ /** Returns the model with the given name on this document's associated connection. */
236
+ model<ModelType extends Model<unknown>>(name: string): ModelType;
237
+ model<ModelType extends Model<DocType, any, any, any>>(): ModelType;
238
+
193
239
  /** Returns the list of paths that have been modified. */
194
240
  modifiedPaths(options?: { includeChildren?: boolean }): Array<string>;
195
241
 
@@ -207,60 +253,95 @@ declare module 'mongoose' {
207
253
  $parent(): Document | undefined;
208
254
 
209
255
  /** Populates document references. */
210
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<MergeType<this, Paths>>;
211
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback<MergeType<this, Paths>>): void;
212
- populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions): Promise<MergeType<this, Paths>>;
213
- populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions, callback?: Callback<MergeType<this, Paths>>): void;
256
+ populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<PopulateDocumentResult<this, Paths, PopulatedPathsDocumentType<DocType, Paths>, DocType>>;
257
+ populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any, any, any, any>, match?: AnyObject, options?: PopulateOptions): Promise<PopulateDocumentResult<this, Paths, PopulatedPathsDocumentType<DocType, Paths>, DocType>>;
214
258
 
215
259
  /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
216
260
  populated(path: string): any;
217
261
 
218
- /** Removes this document from the db. */
219
- remove(options: QueryOptions, callback: Callback): void;
220
- remove(callback: Callback): void;
221
- remove(options?: QueryOptions): Promise<this>;
222
-
223
262
  /** Sends a replaceOne command with this document `_id` as the query selector. */
224
- replaceOne(replacement?: AnyObject, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
263
+ replaceOne(replacement?: AnyObject, options?: QueryOptions | null): Query<any, this>;
225
264
 
226
265
  /** Saves this document by inserting a new document into the database if [document.isNew](/docs/api/document.html#document_Document-isNew) is `true`, or sends an [updateOne](/docs/api/document.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. */
227
- save(options: SaveOptions, callback: Callback<this>): void;
228
- save(callback: Callback<this>): void;
229
266
  save(options?: SaveOptions): Promise<this>;
230
267
 
231
268
  /** The document's schema. */
232
269
  schema: Schema;
233
270
 
234
271
  /** Sets the value of a path, or many paths. */
235
- set(path: string, val: any, type: any, options?: any): this;
236
- set(path: string, val: any, options?: any): this;
237
- set(value: any): this;
272
+ set<T extends keyof DocType>(path: T, val: DocType[T], type: any, options?: DocumentSetOptions): this;
273
+ set(path: string | Record<string, any>, val: any, type: any, options?: DocumentSetOptions): this;
274
+ set(path: string | Record<string, any>, val: any, options?: DocumentSetOptions): this;
275
+ set(value: string | Record<string, any>): this;
276
+
277
+ toBSON(): Require_id<DocType>;
238
278
 
239
279
  /** The return value of this method is used in calls to JSON.stringify(doc). */
240
- toJSON<T = LeanDocument<DocType>>(options?: ToObjectOptions & { flattenMaps?: true }): FlattenMaps<T>;
241
- toJSON<T = LeanDocument<DocType>>(options: ToObjectOptions & { flattenMaps: false }): T;
280
+ toJSON<PopulatedRawDocType, DepopulatedRawDocType>(
281
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
282
+ options: { depopulate: true }
283
+ ): Default__v<Require_id<DepopulatedRawDocType>, TSchemaOptions>;
284
+ toJSON<PopulatedRawDocType, DepopulatedRawDocType, O extends ToObjectOptions & { depopulate: true }>(
285
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
286
+ options: O
287
+ ): ToObjectReturnType<DepopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
288
+ toJSON<PopulatedRawDocType, O extends ToObjectOptions>(
289
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>,
290
+ options: O
291
+ ): ToObjectReturnType<PopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
292
+ toJSON<PopulatedRawDocType>(
293
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>
294
+ ): DefaultToObjectReturnType<PopulatedRawDocType, TVirtuals, TSchemaOptions, 'toJSON'>;
295
+ toJSON<O extends ToObjectOptions>(options: O): ToObjectReturnType<DocType, TVirtuals, O, TSchemaOptions>;
296
+ toJSON(options?: ToObjectOptions): DefaultToObjectReturnType<DocType, TVirtuals, TSchemaOptions, 'toJSON'>;
297
+ toJSON<T>(options?: ToObjectOptions): Default__v<Require_id<T>, ResolveSchemaOptions<TSchemaOptions>>;
242
298
 
243
299
  /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
244
- toObject<T = LeanDocument<DocType>>(options?: ToObjectOptions): Require_id<T>;
300
+ toObject<PopulatedRawDocType, DepopulatedRawDocType>(
301
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
302
+ options: { depopulate: true }
303
+ ): Default__v<Require_id<DepopulatedRawDocType>, TSchemaOptions>;
304
+ toObject<PopulatedRawDocType, DepopulatedRawDocType, O extends ToObjectOptions & { depopulate: true }>(
305
+ this: PopulatedDocumentMarker<PopulatedRawDocType, DepopulatedRawDocType>,
306
+ options: O
307
+ ): ToObjectReturnType<DepopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
308
+ toObject<PopulatedRawDocType, O extends ToObjectOptions>(
309
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>,
310
+ options: O
311
+ ): ToObjectReturnType<PopulatedRawDocType, TVirtuals, O, TSchemaOptions>;
312
+ toObject<PopulatedRawDocType>(
313
+ this: PopulatedDocumentMarker<PopulatedRawDocType, any>
314
+ ): DefaultToObjectReturnType<PopulatedRawDocType, TVirtuals, TSchemaOptions, 'toObject'>;
315
+ toObject<O extends ToObjectOptions>(options: O): ToObjectReturnType<DocType, TVirtuals, O, TSchemaOptions>;
316
+ toObject(options?: ToObjectOptions): DefaultToObjectReturnType<DocType, TVirtuals, TSchemaOptions, 'toObject'>;
317
+ toObject<T>(options?: ToObjectOptions): Default__v<Require_id<T>, ResolveSchemaOptions<TSchemaOptions>>;
245
318
 
246
319
  /** Clears the modified state on the specified path. */
320
+ unmarkModified<T extends keyof DocType>(path: T): void;
247
321
  unmarkModified(path: string): void;
248
322
 
249
- /** Sends an update command with this document `_id` as the query selector. */
250
- update(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
251
-
252
323
  /** Sends an updateOne command with this document `_id` as the query selector. */
253
- updateOne(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
324
+ updateOne(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null): Query<any, this>;
254
325
 
255
326
  /** Executes registered validation rules for this document. */
256
- validate(pathsToValidate: pathsToValidate, options: AnyObject, callback: CallbackWithoutResult): void;
257
- validate(pathsToValidate: pathsToValidate, callback: CallbackWithoutResult): void;
258
- validate(callback: CallbackWithoutResult): void;
259
- validate(pathsToValidate?: pathsToValidate, options?: AnyObject): Promise<void>;
260
- validate(options: { pathsToSkip?: pathsToSkip }): Promise<void>;
261
-
262
- /** Executes registered validation rules (skipping asynchronous validators) for this document. */
263
- validateSync(options: { pathsToSkip?: pathsToSkip, [k: string]: any }): Error.ValidationError | null;
264
- validateSync(pathsToValidate?: pathsToValidate, options?: AnyObject): Error.ValidationError | null;
327
+ validate<T extends keyof DocType>(pathsToValidate?: T | T[], options?: Omit<ValidateOptions, 'pathsToSkip'> & AnyObject): Promise<void>;
328
+ validate(pathsToValidate?: pathsToValidate, options?: Omit<ValidateOptions, 'pathsToSkip'> & AnyObject): Promise<void>;
329
+ validate(options: ValidateOptions): Promise<void>;
330
+
331
+ /**
332
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
333
+ * @deprecated Use `validate()` instead. `validateSync()` does not run middleware and will be removed in Mongoose 10.
334
+ */
335
+ validateSync(options: ValidateSyncOptions): Error.ValidationError | null;
336
+ /**
337
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
338
+ * @deprecated Use `validate()` instead. `validateSync()` does not run middleware and will be removed in Mongoose 10.
339
+ */
340
+ validateSync<T extends keyof DocType>(pathsToValidate?: T | T[], options?: Omit<ValidateSyncOptions, 'pathsToSkip'>): Error.ValidationError | null;
341
+ /**
342
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
343
+ * @deprecated Use `validate()` instead. `validateSync()` does not run middleware and will be removed in Mongoose 10.
344
+ */
345
+ validateSync(pathsToValidate?: pathsToValidate, options?: Omit<ValidateSyncOptions, 'pathsToSkip'>): Error.ValidationError | null;
265
346
  }
266
347
  }