@depup/mongoose 9.1.3-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 (295) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +397 -0
  3. package/SECURITY.md +1 -0
  4. package/eslint.config.mjs +198 -0
  5. package/index.js +64 -0
  6. package/lib/aggregate.js +1189 -0
  7. package/lib/cast/bigint.js +46 -0
  8. package/lib/cast/boolean.js +32 -0
  9. package/lib/cast/date.js +41 -0
  10. package/lib/cast/decimal128.js +39 -0
  11. package/lib/cast/double.js +50 -0
  12. package/lib/cast/int32.js +36 -0
  13. package/lib/cast/number.js +42 -0
  14. package/lib/cast/objectid.js +29 -0
  15. package/lib/cast/string.js +37 -0
  16. package/lib/cast/uuid.js +35 -0
  17. package/lib/cast.js +436 -0
  18. package/lib/collection.js +321 -0
  19. package/lib/connection.js +1855 -0
  20. package/lib/connectionState.js +26 -0
  21. package/lib/constants.js +73 -0
  22. package/lib/cursor/aggregationCursor.js +466 -0
  23. package/lib/cursor/changeStream.js +198 -0
  24. package/lib/cursor/queryCursor.js +622 -0
  25. package/lib/document.js +5521 -0
  26. package/lib/driver.js +15 -0
  27. package/lib/drivers/SPEC.md +4 -0
  28. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  29. package/lib/drivers/node-mongodb-native/collection.js +393 -0
  30. package/lib/drivers/node-mongodb-native/connection.js +506 -0
  31. package/lib/drivers/node-mongodb-native/index.js +10 -0
  32. package/lib/error/browserMissingSchema.js +29 -0
  33. package/lib/error/bulkSaveIncompleteError.js +44 -0
  34. package/lib/error/bulkWriteError.js +41 -0
  35. package/lib/error/cast.js +158 -0
  36. package/lib/error/createCollectionsError.js +26 -0
  37. package/lib/error/divergentArray.js +40 -0
  38. package/lib/error/eachAsyncMultiError.js +41 -0
  39. package/lib/error/index.js +237 -0
  40. package/lib/error/invalidSchemaOption.js +32 -0
  41. package/lib/error/messages.js +47 -0
  42. package/lib/error/missingSchema.js +33 -0
  43. package/lib/error/mongooseError.js +13 -0
  44. package/lib/error/notFound.js +47 -0
  45. package/lib/error/objectExpected.js +31 -0
  46. package/lib/error/objectParameter.js +31 -0
  47. package/lib/error/overwriteModel.js +31 -0
  48. package/lib/error/parallelSave.js +33 -0
  49. package/lib/error/parallelValidate.js +33 -0
  50. package/lib/error/serverSelection.js +62 -0
  51. package/lib/error/setOptionError.js +103 -0
  52. package/lib/error/strict.js +35 -0
  53. package/lib/error/strictPopulate.js +31 -0
  54. package/lib/error/syncIndexes.js +30 -0
  55. package/lib/error/validation.js +97 -0
  56. package/lib/error/validator.js +100 -0
  57. package/lib/error/version.js +38 -0
  58. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +39 -0
  59. package/lib/helpers/aggregate/stringifyFunctionOperators.js +50 -0
  60. package/lib/helpers/arrayDepth.js +33 -0
  61. package/lib/helpers/clone.js +204 -0
  62. package/lib/helpers/common.js +127 -0
  63. package/lib/helpers/createJSONSchemaTypeDefinition.js +24 -0
  64. package/lib/helpers/cursor/eachAsync.js +225 -0
  65. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  66. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +16 -0
  67. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +12 -0
  68. package/lib/helpers/discriminator/getConstructor.js +29 -0
  69. package/lib/helpers/discriminator/getDiscriminatorByValue.js +28 -0
  70. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +27 -0
  71. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +91 -0
  72. package/lib/helpers/document/applyDefaults.js +132 -0
  73. package/lib/helpers/document/applyTimestamps.js +106 -0
  74. package/lib/helpers/document/applyVirtuals.js +147 -0
  75. package/lib/helpers/document/cleanModifiedSubpaths.js +45 -0
  76. package/lib/helpers/document/compile.js +238 -0
  77. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  78. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +53 -0
  79. package/lib/helpers/document/handleSpreadDoc.js +35 -0
  80. package/lib/helpers/each.js +25 -0
  81. package/lib/helpers/error/combinePathErrors.js +22 -0
  82. package/lib/helpers/firstKey.js +8 -0
  83. package/lib/helpers/get.js +65 -0
  84. package/lib/helpers/getConstructorName.js +16 -0
  85. package/lib/helpers/getDefaultBulkwriteResult.js +18 -0
  86. package/lib/helpers/getFunctionName.js +10 -0
  87. package/lib/helpers/immediate.js +16 -0
  88. package/lib/helpers/indexes/applySchemaCollation.js +13 -0
  89. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +14 -0
  90. package/lib/helpers/indexes/getRelatedIndexes.js +63 -0
  91. package/lib/helpers/indexes/isDefaultIdIndex.js +18 -0
  92. package/lib/helpers/indexes/isIndexEqual.js +95 -0
  93. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  94. package/lib/helpers/indexes/isTextIndex.js +16 -0
  95. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  96. package/lib/helpers/isAsyncFunction.js +9 -0
  97. package/lib/helpers/isBsonType.js +15 -0
  98. package/lib/helpers/isMongooseObject.js +22 -0
  99. package/lib/helpers/isObject.js +16 -0
  100. package/lib/helpers/isPOJO.js +12 -0
  101. package/lib/helpers/isPromise.js +6 -0
  102. package/lib/helpers/isSimpleValidator.js +22 -0
  103. package/lib/helpers/minimize.js +41 -0
  104. package/lib/helpers/model/applyDefaultsToPOJO.js +52 -0
  105. package/lib/helpers/model/applyHooks.js +140 -0
  106. package/lib/helpers/model/applyMethods.js +70 -0
  107. package/lib/helpers/model/applyStaticHooks.js +33 -0
  108. package/lib/helpers/model/applyStatics.js +13 -0
  109. package/lib/helpers/model/castBulkWrite.js +316 -0
  110. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  111. package/lib/helpers/model/discriminator.js +265 -0
  112. package/lib/helpers/model/pushNestedArrayPaths.js +15 -0
  113. package/lib/helpers/omitUndefined.js +20 -0
  114. package/lib/helpers/once.js +12 -0
  115. package/lib/helpers/parallelLimit.js +37 -0
  116. package/lib/helpers/path/parentPaths.js +18 -0
  117. package/lib/helpers/path/setDottedPath.js +33 -0
  118. package/lib/helpers/pluralize.js +95 -0
  119. package/lib/helpers/populate/assignRawDocsToIdStructure.js +129 -0
  120. package/lib/helpers/populate/assignVals.js +360 -0
  121. package/lib/helpers/populate/createPopulateQueryFilter.js +97 -0
  122. package/lib/helpers/populate/getModelsMapForPopulate.js +776 -0
  123. package/lib/helpers/populate/getSchemaTypes.js +228 -0
  124. package/lib/helpers/populate/getVirtual.js +103 -0
  125. package/lib/helpers/populate/leanPopulateMap.js +7 -0
  126. package/lib/helpers/populate/lookupLocalFields.js +40 -0
  127. package/lib/helpers/populate/markArraySubdocsPopulated.js +49 -0
  128. package/lib/helpers/populate/modelNamesFromRefPath.js +66 -0
  129. package/lib/helpers/populate/removeDeselectedForeignField.js +31 -0
  130. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  131. package/lib/helpers/populate/skipPopulateValue.js +10 -0
  132. package/lib/helpers/populate/validateRef.js +19 -0
  133. package/lib/helpers/printJestWarning.js +21 -0
  134. package/lib/helpers/processConnectionOptions.js +65 -0
  135. package/lib/helpers/projection/applyProjection.js +83 -0
  136. package/lib/helpers/projection/hasIncludedChildren.js +41 -0
  137. package/lib/helpers/projection/isDefiningProjection.js +18 -0
  138. package/lib/helpers/projection/isExclusive.js +37 -0
  139. package/lib/helpers/projection/isInclusive.js +39 -0
  140. package/lib/helpers/projection/isNestedProjection.js +8 -0
  141. package/lib/helpers/projection/isPathExcluded.js +40 -0
  142. package/lib/helpers/projection/isPathSelectedInclusive.js +28 -0
  143. package/lib/helpers/projection/isSubpath.js +14 -0
  144. package/lib/helpers/projection/parseProjection.js +33 -0
  145. package/lib/helpers/query/applyGlobalOption.js +29 -0
  146. package/lib/helpers/query/cast$expr.js +287 -0
  147. package/lib/helpers/query/castFilterPath.js +54 -0
  148. package/lib/helpers/query/castUpdate.js +643 -0
  149. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +103 -0
  150. package/lib/helpers/query/handleImmutable.js +44 -0
  151. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  152. package/lib/helpers/query/hasDollarKeys.js +23 -0
  153. package/lib/helpers/query/isOperator.js +14 -0
  154. package/lib/helpers/query/sanitizeFilter.js +38 -0
  155. package/lib/helpers/query/sanitizeProjection.js +14 -0
  156. package/lib/helpers/query/selectPopulatedFields.js +62 -0
  157. package/lib/helpers/query/trusted.js +13 -0
  158. package/lib/helpers/query/validOps.js +3 -0
  159. package/lib/helpers/schema/addAutoId.js +7 -0
  160. package/lib/helpers/schema/applyBuiltinPlugins.js +12 -0
  161. package/lib/helpers/schema/applyPlugins.js +55 -0
  162. package/lib/helpers/schema/applyReadConcern.js +20 -0
  163. package/lib/helpers/schema/applyWriteConcern.js +39 -0
  164. package/lib/helpers/schema/cleanPositionalOperators.js +12 -0
  165. package/lib/helpers/schema/getIndexes.js +171 -0
  166. package/lib/helpers/schema/getKeysInSchemaOrder.js +28 -0
  167. package/lib/helpers/schema/getPath.js +43 -0
  168. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  169. package/lib/helpers/schema/handleIdOption.js +20 -0
  170. package/lib/helpers/schema/handleTimestampOption.js +24 -0
  171. package/lib/helpers/schema/idGetter.js +34 -0
  172. package/lib/helpers/schema/merge.js +36 -0
  173. package/lib/helpers/schematype/handleImmutable.js +50 -0
  174. package/lib/helpers/setDefaultsOnInsert.js +158 -0
  175. package/lib/helpers/specialProperties.js +3 -0
  176. package/lib/helpers/symbols.js +20 -0
  177. package/lib/helpers/timers.js +3 -0
  178. package/lib/helpers/timestamps/setDocumentTimestamps.js +26 -0
  179. package/lib/helpers/timestamps/setupTimestamps.js +116 -0
  180. package/lib/helpers/topology/allServersUnknown.js +12 -0
  181. package/lib/helpers/topology/isAtlas.js +31 -0
  182. package/lib/helpers/topology/isSSLError.js +16 -0
  183. package/lib/helpers/update/applyTimestampsToChildren.js +193 -0
  184. package/lib/helpers/update/applyTimestampsToUpdate.js +131 -0
  185. package/lib/helpers/update/castArrayFilters.js +113 -0
  186. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  187. package/lib/helpers/update/modifiedPaths.js +33 -0
  188. package/lib/helpers/update/moveImmutableProperties.js +53 -0
  189. package/lib/helpers/update/removeUnusedArrayFilters.js +32 -0
  190. package/lib/helpers/update/updatedPathsByArrayFilter.js +27 -0
  191. package/lib/helpers/updateValidators.js +193 -0
  192. package/lib/index.js +17 -0
  193. package/lib/internal.js +46 -0
  194. package/lib/model.js +5010 -0
  195. package/lib/modifiedPathsSnapshot.js +9 -0
  196. package/lib/mongoose.js +1411 -0
  197. package/lib/options/populateOptions.js +36 -0
  198. package/lib/options/propertyOptions.js +8 -0
  199. package/lib/options/saveOptions.js +16 -0
  200. package/lib/options/schemaArrayOptions.js +78 -0
  201. package/lib/options/schemaBufferOptions.js +38 -0
  202. package/lib/options/schemaDateOptions.js +71 -0
  203. package/lib/options/schemaDocumentArrayOptions.js +68 -0
  204. package/lib/options/schemaMapOptions.js +43 -0
  205. package/lib/options/schemaNumberOptions.js +101 -0
  206. package/lib/options/schemaObjectIdOptions.js +64 -0
  207. package/lib/options/schemaStringOptions.js +138 -0
  208. package/lib/options/schemaSubdocumentOptions.js +66 -0
  209. package/lib/options/schemaTypeOptions.js +244 -0
  210. package/lib/options/schemaUnionOptions.js +32 -0
  211. package/lib/options/virtualOptions.js +164 -0
  212. package/lib/options.js +17 -0
  213. package/lib/plugins/index.js +6 -0
  214. package/lib/plugins/saveSubdocs.js +76 -0
  215. package/lib/plugins/sharding.js +84 -0
  216. package/lib/plugins/trackTransaction.js +84 -0
  217. package/lib/plugins/validateBeforeSave.js +41 -0
  218. package/lib/query.js +5673 -0
  219. package/lib/queryHelpers.js +387 -0
  220. package/lib/schema/array.js +699 -0
  221. package/lib/schema/bigint.js +282 -0
  222. package/lib/schema/boolean.js +332 -0
  223. package/lib/schema/buffer.js +343 -0
  224. package/lib/schema/date.js +467 -0
  225. package/lib/schema/decimal128.js +263 -0
  226. package/lib/schema/documentArray.js +656 -0
  227. package/lib/schema/documentArrayElement.js +137 -0
  228. package/lib/schema/double.js +246 -0
  229. package/lib/schema/index.js +32 -0
  230. package/lib/schema/int32.js +289 -0
  231. package/lib/schema/map.js +201 -0
  232. package/lib/schema/mixed.js +146 -0
  233. package/lib/schema/number.js +510 -0
  234. package/lib/schema/objectId.js +333 -0
  235. package/lib/schema/operators/bitwise.js +38 -0
  236. package/lib/schema/operators/exists.js +12 -0
  237. package/lib/schema/operators/geospatial.js +107 -0
  238. package/lib/schema/operators/helpers.js +32 -0
  239. package/lib/schema/operators/text.js +39 -0
  240. package/lib/schema/operators/type.js +20 -0
  241. package/lib/schema/string.js +733 -0
  242. package/lib/schema/subdocument.js +436 -0
  243. package/lib/schema/symbols.js +5 -0
  244. package/lib/schema/union.js +113 -0
  245. package/lib/schema/uuid.js +305 -0
  246. package/lib/schema.js +3226 -0
  247. package/lib/schemaType.js +1835 -0
  248. package/lib/stateMachine.js +232 -0
  249. package/lib/types/array/index.js +119 -0
  250. package/lib/types/array/isMongooseArray.js +5 -0
  251. package/lib/types/array/methods/index.js +1095 -0
  252. package/lib/types/arraySubdocument.js +207 -0
  253. package/lib/types/buffer.js +294 -0
  254. package/lib/types/decimal128.js +13 -0
  255. package/lib/types/documentArray/index.js +113 -0
  256. package/lib/types/documentArray/isMongooseDocumentArray.js +5 -0
  257. package/lib/types/documentArray/methods/index.js +415 -0
  258. package/lib/types/double.js +13 -0
  259. package/lib/types/index.js +23 -0
  260. package/lib/types/map.js +419 -0
  261. package/lib/types/objectid.js +41 -0
  262. package/lib/types/subdocument.js +464 -0
  263. package/lib/types/uuid.js +13 -0
  264. package/lib/utils.js +1054 -0
  265. package/lib/validOptions.js +42 -0
  266. package/lib/virtualType.js +204 -0
  267. package/package.json +148 -0
  268. package/types/aggregate.d.ts +180 -0
  269. package/types/augmentations.d.ts +9 -0
  270. package/types/callback.d.ts +8 -0
  271. package/types/collection.d.ts +49 -0
  272. package/types/connection.d.ts +297 -0
  273. package/types/cursor.d.ts +67 -0
  274. package/types/document.d.ts +374 -0
  275. package/types/error.d.ts +143 -0
  276. package/types/expressions.d.ts +3053 -0
  277. package/types/helpers.d.ts +32 -0
  278. package/types/index.d.ts +1056 -0
  279. package/types/indexes.d.ts +97 -0
  280. package/types/inferhydrateddoctype.d.ts +115 -0
  281. package/types/inferrawdoctype.d.ts +135 -0
  282. package/types/inferschematype.d.ts +337 -0
  283. package/types/middlewares.d.ts +59 -0
  284. package/types/models.d.ts +1306 -0
  285. package/types/mongooseoptions.d.ts +228 -0
  286. package/types/pipelinestage.d.ts +333 -0
  287. package/types/populate.d.ts +53 -0
  288. package/types/query.d.ts +934 -0
  289. package/types/schemaoptions.d.ts +282 -0
  290. package/types/schematypes.d.ts +654 -0
  291. package/types/session.d.ts +32 -0
  292. package/types/types.d.ts +109 -0
  293. package/types/utility.d.ts +175 -0
  294. package/types/validation.d.ts +39 -0
  295. package/types/virtuals.d.ts +14 -0
package/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2010-2013 LearnBoost <dev@learnboost.com>
4
+ Copyright (c) 2013-2021 Automattic
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,397 @@
1
+ # Mongoose
2
+
3
+ Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. Mongoose supports [Node.js](https://nodejs.org/en/) and [Deno](https://deno.land/) (alpha).
4
+
5
+ [![Build Status](https://github.com/Automattic/mongoose/workflows/Test/badge.svg)](https://github.com/Automattic/mongoose)
6
+ [![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
7
+ [![Deno version](https://deno.land/badge/mongoose/version)](https://deno.land/x/mongoose)
8
+ [![Deno popularity](https://deno.land/badge/mongoose/popularity)](https://deno.land/x/mongoose)
9
+
10
+ [![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose)
11
+
12
+ ## Documentation
13
+
14
+ The official documentation website is [mongoosejs.com](http://mongoosejs.com/).
15
+
16
+ Mongoose 9.0.0 was released on November 21, 2025. You can find more details on [backwards breaking changes in 9.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_9.html).
17
+
18
+ ## Support
19
+
20
+ * [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
21
+ * [Bug Reports](https://github.com/Automattic/mongoose/issues/)
22
+ * [Mongoose Slack Channel](http://slack.mongoosejs.io/)
23
+ * [Help Forum](http://groups.google.com/group/mongoose-orm)
24
+ * [MongoDB Support](https://www.mongodb.com/docs/manual/support/)
25
+
26
+ ## Plugins
27
+
28
+ Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins).
29
+
30
+ ## Contributors
31
+
32
+ Pull requests are always welcome! Please base pull requests against the `master`
33
+ branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md).
34
+
35
+ If your pull requests makes documentation changes, please do **not**
36
+ modify any `.html` files. The `.html` files are compiled code, so please make
37
+ your changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`.
38
+
39
+ View all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).
40
+
41
+ ## Installation
42
+
43
+ First install [Node.js](http://nodejs.org/) and [MongoDB](https://www.mongodb.org/downloads). Then:
44
+
45
+ Then install the `mongoose` package using your preferred package manager:
46
+
47
+ ### Using npm
48
+
49
+ ```sh
50
+ npm install mongoose
51
+ ```
52
+
53
+ ### Using pnpm
54
+
55
+ ```sh
56
+ pnpm add mongoose
57
+ ```
58
+
59
+ ### Using Yarn
60
+
61
+ ```sh
62
+ yarn add mongoose
63
+ ```
64
+
65
+ ### Using Bun
66
+
67
+ ```sh
68
+ bun add mongoose
69
+ ```
70
+
71
+ Mongoose 6.8.0 also includes alpha support for [Deno](https://deno.land/).
72
+
73
+ ## Importing
74
+
75
+ ```javascript
76
+ // Using Node.js `require()`
77
+ const mongoose = require('mongoose');
78
+
79
+ // Using ES6 imports
80
+ import mongoose from 'mongoose';
81
+ ```
82
+
83
+ Or, using [Deno's `createRequire()` for CommonJS support](https://deno.land/std@0.113.0/node/README.md?source=#commonjs-modules-loading) as follows.
84
+
85
+ ```javascript
86
+ import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts';
87
+ const require = createRequire(import.meta.url);
88
+
89
+ const mongoose = require('mongoose');
90
+
91
+ mongoose.connect('mongodb://127.0.0.1:27017/test')
92
+ .then(() => console.log('Connected!'));
93
+ ```
94
+
95
+ You can then run the above script using the following.
96
+
97
+ ```sh
98
+ deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js
99
+ ```
100
+
101
+ ## Mongoose for Enterprise
102
+
103
+ Available as part of the Tidelift Subscription
104
+
105
+ The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-mongoose?utm_source=npm-mongoose&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
106
+
107
+ ## Overview
108
+
109
+ ### Connecting to MongoDB
110
+
111
+ First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
112
+
113
+ Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
114
+
115
+ ```js
116
+ await mongoose.connect('mongodb://127.0.0.1/my_database');
117
+ ```
118
+
119
+ Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
120
+
121
+ **Note:** *If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.*
122
+
123
+ **Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
124
+
125
+ ### Defining a Model
126
+
127
+ Models are defined through the `Schema` interface.
128
+
129
+ ```js
130
+ const Schema = mongoose.Schema;
131
+ const ObjectId = Schema.ObjectId;
132
+
133
+ const BlogPost = new Schema({
134
+ author: ObjectId,
135
+ title: String,
136
+ body: String,
137
+ date: Date
138
+ });
139
+ ```
140
+
141
+ Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
142
+
143
+ * [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
144
+ * [Defaults](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-default)
145
+ * [Getters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-get)
146
+ * [Setters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set)
147
+ * [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
148
+ * [Middleware](http://mongoosejs.com/docs/middleware.html)
149
+ * [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
150
+ * [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
151
+ * [Plugins](http://mongoosejs.com/docs/plugins.html)
152
+ * [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
153
+
154
+ The following example shows some of these features:
155
+
156
+ ```js
157
+ const Comment = new Schema({
158
+ name: { type: String, default: 'hahaha' },
159
+ age: { type: Number, min: 18, index: true },
160
+ bio: { type: String, match: /[a-z]/ },
161
+ date: { type: Date, default: Date.now },
162
+ buff: Buffer
163
+ });
164
+
165
+ // a setter
166
+ Comment.path('name').set(function(v) {
167
+ return capitalize(v);
168
+ });
169
+
170
+ // middleware
171
+ Comment.pre('save', function(next) {
172
+ notify(this.get('email'));
173
+ next();
174
+ });
175
+ ```
176
+
177
+ Take a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js) for an end-to-end example of a typical setup.
178
+
179
+ ### Accessing a Model
180
+
181
+ Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
182
+
183
+ ```js
184
+ const MyModel = mongoose.model('ModelName');
185
+ ```
186
+
187
+ Or just do it all at once
188
+
189
+ ```js
190
+ const MyModel = mongoose.model('ModelName', mySchema);
191
+ ```
192
+
193
+ The first argument is the *singular* name of the collection your model is for. **Mongoose automatically looks for the *plural* version of your model name.** For example, if you use
194
+
195
+ ```js
196
+ const MyModel = mongoose.model('Ticket', mySchema);
197
+ ```
198
+
199
+ Then `MyModel` will use the **tickets** collection, not the **ticket** collection. For more details read the [model docs](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-model).
200
+
201
+ Once we have our model, we can then instantiate it, and save it:
202
+
203
+ ```js
204
+ const instance = new MyModel();
205
+ instance.my.key = 'hello';
206
+ await instance.save();
207
+ ```
208
+
209
+ Or we can find documents from the same collection
210
+
211
+ ```js
212
+ await MyModel.find({});
213
+ ```
214
+
215
+ You can also `findOne`, `findById`, `update`, etc.
216
+
217
+ ```js
218
+ const instance = await MyModel.findOne({ /* ... */ });
219
+ console.log(instance.my.key); // 'hello'
220
+ ```
221
+
222
+ For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
223
+
224
+ **Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
225
+
226
+ ```js
227
+ const conn = mongoose.createConnection('your connection string');
228
+ const MyModel = conn.model('ModelName', schema);
229
+ const m = new MyModel();
230
+ await m.save(); // works
231
+ ```
232
+
233
+ vs
234
+
235
+ ```js
236
+ const conn = mongoose.createConnection('your connection string');
237
+ const MyModel = mongoose.model('ModelName', schema);
238
+ const m = new MyModel();
239
+ await m.save(); // does not work b/c the default connection object was never connected
240
+ ```
241
+
242
+ ### Embedded Documents
243
+
244
+ In the first example snippet, we defined a key in the Schema that looks like:
245
+
246
+ ```txt
247
+ comments: [Comment]
248
+ ```
249
+
250
+ Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:
251
+
252
+ ```js
253
+ // retrieve my model
254
+ const BlogPost = mongoose.model('BlogPost');
255
+
256
+ // create a blog post
257
+ const post = new BlogPost();
258
+
259
+ // create a comment
260
+ post.comments.push({ title: 'My comment' });
261
+
262
+ await post.save();
263
+ ```
264
+
265
+ The same goes for removing them:
266
+
267
+ ```js
268
+ const post = await BlogPost.findById(myId);
269
+ post.comments[0].deleteOne();
270
+ await post.save();
271
+ ```
272
+
273
+ Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.
274
+
275
+ ### Middleware
276
+
277
+ See the [docs](http://mongoosejs.com/docs/middleware.html) page.
278
+
279
+ #### Intercepting and mutating method arguments
280
+
281
+ You can intercept method arguments via middleware.
282
+
283
+ For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:
284
+
285
+ ```js
286
+ schema.pre('set', function(next, path, val, typel) {
287
+ // `this` is the current Document
288
+ this.emit('set', path, val);
289
+
290
+ // Pass control to the next pre
291
+ next();
292
+ });
293
+ ```
294
+
295
+ Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`:
296
+
297
+ ```js
298
+ schema.pre(method, function firstPre(next, methodArg1, methodArg2) {
299
+ // Mutate methodArg1
300
+ next('altered-' + methodArg1.toString(), methodArg2);
301
+ });
302
+
303
+ // pre declaration is chainable
304
+ schema.pre(method, function secondPre(next, methodArg1, methodArg2) {
305
+ console.log(methodArg1);
306
+ // => 'altered-originalValOfMethodArg1'
307
+
308
+ console.log(methodArg2);
309
+ // => 'originalValOfMethodArg2'
310
+
311
+ // Passing no arguments to `next` automatically passes along the current argument values
312
+ // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
313
+ // and also equivalent to, with the example method arg
314
+ // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
315
+ next();
316
+ });
317
+ ```
318
+
319
+ #### Schema gotcha
320
+
321
+ `type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation:
322
+
323
+ ```js
324
+ new Schema({
325
+ broken: { type: Boolean },
326
+ asset: {
327
+ name: String,
328
+ type: String // uh oh, it broke. asset will be interpreted as String
329
+ }
330
+ });
331
+
332
+ new Schema({
333
+ works: { type: Boolean },
334
+ asset: {
335
+ name: String,
336
+ type: { type: String } // works. asset is an object with a type property
337
+ }
338
+ });
339
+ ```
340
+
341
+ ### Driver Access
342
+
343
+ Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one
344
+ notable exception that `YourModel.collection` still buffers
345
+ commands. As such, `YourModel.collection.find()` will **not**
346
+ return a cursor.
347
+
348
+ ## API Docs
349
+
350
+ [Mongoose API documentation](http://mongoosejs.com/docs/api/mongoose.html), generated using [dox](https://github.com/tj/dox)
351
+ and [acquit](https://github.com/vkarpov15/acquit).
352
+
353
+ ## Related Projects
354
+
355
+ ### MongoDB Runners
356
+
357
+ * [run-rs](https://www.npmjs.com/package/run-rs)
358
+ * [mongodb-memory-server](https://www.npmjs.com/package/mongodb-memory-server)
359
+ * [mongodb-topology-manager](https://www.npmjs.com/package/mongodb-topology-manager)
360
+
361
+ ### Unofficial CLIs
362
+
363
+ * [mongoosejs-cli](https://www.npmjs.com/package/mongoosejs-cli)
364
+
365
+ ### Data Seeding
366
+
367
+ * [dookie](https://www.npmjs.com/package/dookie)
368
+ * [seedgoose](https://www.npmjs.com/package/seedgoose)
369
+ * [mongoose-data-seed](https://www.npmjs.com/package/mongoose-data-seed)
370
+
371
+ ### Express Session Stores
372
+
373
+ * [connect-mongodb-session](https://www.npmjs.com/package/connect-mongodb-session)
374
+ * [connect-mongo](https://www.npmjs.com/package/connect-mongo)
375
+
376
+ ## License
377
+
378
+ Copyright (c) 2010 LearnBoost &lt;dev@learnboost.com&gt;
379
+
380
+ Permission is hereby granted, free of charge, to any person obtaining
381
+ a copy of this software and associated documentation files (the
382
+ 'Software'), to deal in the Software without restriction, including
383
+ without limitation the rights to use, copy, modify, merge, publish,
384
+ distribute, sublicense, and/or sell copies of the Software, and to
385
+ permit persons to whom the Software is furnished to do so, subject to
386
+ the following conditions:
387
+
388
+ The above copyright notice and this permission notice shall be
389
+ included in all copies or substantial portions of the Software.
390
+
391
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
392
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
393
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
394
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
395
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
396
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
397
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/SECURITY.md ADDED
@@ -0,0 +1 @@
1
+ Please follow the instructions on [Tidelift's security page](https://tidelift.com/docs/security) to report a security issue.
@@ -0,0 +1,198 @@
1
+ import { defineConfig, globalIgnores } from 'eslint/config';
2
+ import mochaNoOnly from 'eslint-plugin-mocha-no-only';
3
+ import globals from 'globals';
4
+ import tseslint from 'typescript-eslint';
5
+ import js from '@eslint/js';
6
+
7
+ export default defineConfig([
8
+ globalIgnores([
9
+ '**/tools',
10
+ '**/dist',
11
+ 'test/files/*',
12
+ '**/benchmarks',
13
+ '**/*.min.js',
14
+ '**/docs/js/native.js',
15
+ '!**/.*',
16
+ '**/node_modules',
17
+ '**/.git',
18
+ '**/data'
19
+ ]),
20
+ js.configs.recommended,
21
+ // general options
22
+ {
23
+ languageOptions: {
24
+ globals: globals.node,
25
+ ecmaVersion: 2022, // nodejs 18.0.0,
26
+ sourceType: 'commonjs'
27
+ },
28
+ rules: {
29
+ 'comma-style': 'error',
30
+
31
+ indent: ['error', 2, {
32
+ SwitchCase: 1,
33
+ VariableDeclarator: 2
34
+ }],
35
+
36
+ 'keyword-spacing': 'error',
37
+ 'no-whitespace-before-property': 'error',
38
+ 'no-buffer-constructor': 'warn',
39
+ 'no-console': 'off',
40
+ 'no-constant-condition': 'off',
41
+ 'no-multi-spaces': 'error',
42
+ 'func-call-spacing': 'error',
43
+ 'no-trailing-spaces': 'error',
44
+ 'no-undef': 'error',
45
+ 'no-unneeded-ternary': 'error',
46
+ 'no-const-assign': 'error',
47
+ 'no-useless-rename': 'error',
48
+ 'no-dupe-keys': 'error',
49
+ 'space-in-parens': ['error', 'never'],
50
+
51
+ 'spaced-comment': ['error', 'always', {
52
+ block: {
53
+ markers: ['!'],
54
+ balanced: true
55
+ }
56
+ }],
57
+
58
+ 'key-spacing': ['error', {
59
+ beforeColon: false,
60
+ afterColon: true
61
+ }],
62
+
63
+ 'comma-spacing': ['error', {
64
+ before: false,
65
+ after: true
66
+ }],
67
+
68
+ 'array-bracket-spacing': 1,
69
+
70
+ 'arrow-spacing': ['error', {
71
+ before: true,
72
+ after: true
73
+ }],
74
+
75
+ 'object-curly-spacing': ['error', 'always'],
76
+ 'comma-dangle': ['error', 'never'],
77
+ 'no-unreachable': 'error',
78
+ quotes: ['error', 'single'],
79
+ 'quote-props': ['error', 'as-needed'],
80
+ semi: 'error',
81
+ 'no-extra-semi': 'error',
82
+ 'semi-spacing': 'error',
83
+ 'no-spaced-func': 'error',
84
+ 'no-throw-literal': 'error',
85
+ 'space-before-blocks': 'error',
86
+ 'space-before-function-paren': ['error', 'never'],
87
+ 'space-infix-ops': 'error',
88
+ 'space-unary-ops': 'error',
89
+ 'no-var': 'warn',
90
+ 'prefer-const': 'warn',
91
+ strict: ['error', 'global'],
92
+
93
+ 'no-restricted-globals': ['error', {
94
+ name: 'context',
95
+ message: 'Don\'t use Mocha\'s global context'
96
+ }],
97
+
98
+ 'no-prototype-builtins': 'off',
99
+ 'no-empty': 'off',
100
+ 'eol-last': 'warn',
101
+
102
+ 'no-multiple-empty-lines': ['warn', {
103
+ max: 2
104
+ }]
105
+ }
106
+ },
107
+ // general typescript options
108
+ {
109
+ files: ['**/*.{ts,tsx}', '**/*.md/*.ts', '**/*.md/*.typescript'],
110
+ extends: [
111
+ tseslint.configs.recommended
112
+ ],
113
+ languageOptions: {
114
+ parserOptions: {
115
+ projectService: {
116
+ allowDefaultProject: [],
117
+ defaultProject: 'tsconfig.json'
118
+ }
119
+ }
120
+ },
121
+ rules: {
122
+ '@typescript-eslint/triple-slash-reference': 'off',
123
+ '@typescript-eslint/no-non-null-assertion': 'off',
124
+ '@typescript-eslint/no-empty-function': 'off',
125
+
126
+ 'spaced-comment': ['error', 'always', {
127
+ block: {
128
+ markers: ['!'],
129
+ balanced: true
130
+ },
131
+
132
+ markers: ['/']
133
+ }],
134
+
135
+ '@typescript-eslint/no-explicit-any': 'off',
136
+ '@typescript-eslint/ban-types': 'off',
137
+ '@typescript-eslint/no-unused-vars': 'off',
138
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
139
+ '@typescript-eslint/prefer-optional-chain': 'error',
140
+ '@typescript-eslint/no-dupe-class-members': 'error',
141
+ '@typescript-eslint/no-redeclare': 'error',
142
+ '@typescript-eslint/space-infix-ops': 'off',
143
+ '@typescript-eslint/no-require-imports': 'off',
144
+ '@typescript-eslint/no-empty-object-type': 'off',
145
+ '@typescript-eslint/no-wrapper-object-types': 'off',
146
+ '@typescript-eslint/no-unused-expressions': 'off',
147
+ '@typescript-eslint/no-unsafe-function-type': 'off'
148
+ }
149
+ },
150
+ // type test specific options
151
+ {
152
+ files: ['test/types/**/*.ts'],
153
+ rules: {
154
+ '@typescript-eslint/no-empty-interface': 'off'
155
+ }
156
+ },
157
+ // test specific options (including type tests)
158
+ {
159
+ files: ['test/**/*.js', 'test/**/*.ts'],
160
+ ignores: ['deno*.mjs'],
161
+ plugins: {
162
+ 'mocha-no-only': mochaNoOnly
163
+ },
164
+ languageOptions: {
165
+ globals: globals.mocha
166
+ },
167
+ rules: {
168
+ 'no-self-assign': 'off',
169
+ 'mocha-no-only/mocha-no-only': ['error']
170
+ }
171
+ },
172
+ // deno specific options
173
+ {
174
+ files: ['**/deno*.mjs'],
175
+ languageOptions: {
176
+ globals: {
177
+ // "globals" currently has no definition for deno
178
+ Deno: 'readonly'
179
+ }
180
+ }
181
+ },
182
+ // general options for module files
183
+ {
184
+ files: ['**/*.mjs'],
185
+ languageOptions: {
186
+ sourceType: 'module'
187
+ }
188
+ },
189
+ // doc script specific options
190
+ {
191
+ files: ['**/docs/js/**/*.js'],
192
+ languageOptions: {
193
+ globals: {
194
+ ...Object.fromEntries(Object.entries(globals.node).map(([key]) => [key, 'off'])),
195
+ ...globals.browser }
196
+ }
197
+ }
198
+ ]);
package/index.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Export lib/mongoose
3
+ *
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ const mongoose = require('./lib/');
9
+
10
+ module.exports = mongoose;
11
+ module.exports.default = mongoose;
12
+ module.exports.mongoose = mongoose;
13
+
14
+ // Re-export for ESM support
15
+ module.exports.cast = mongoose.cast;
16
+ module.exports.STATES = mongoose.STATES;
17
+ module.exports.setDriver = mongoose.setDriver;
18
+ module.exports.set = mongoose.set;
19
+ module.exports.get = mongoose.get;
20
+ module.exports.createConnection = mongoose.createConnection;
21
+ module.exports.connect = mongoose.connect;
22
+ module.exports.disconnect = mongoose.disconnect;
23
+ module.exports.startSession = mongoose.startSession;
24
+ module.exports.pluralize = mongoose.pluralize;
25
+ module.exports.model = mongoose.model;
26
+ module.exports.deleteModel = mongoose.deleteModel;
27
+ module.exports.modelNames = mongoose.modelNames;
28
+ module.exports.plugin = mongoose.plugin;
29
+ module.exports.connections = mongoose.connections;
30
+ module.exports.version = mongoose.version;
31
+ module.exports.Aggregate = mongoose.Aggregate;
32
+ module.exports.Mongoose = mongoose.Mongoose;
33
+ module.exports.Schema = mongoose.Schema;
34
+ module.exports.SchemaType = mongoose.SchemaType;
35
+ module.exports.SchemaTypes = mongoose.SchemaTypes;
36
+ module.exports.VirtualType = mongoose.VirtualType;
37
+ module.exports.Types = mongoose.Types;
38
+ module.exports.Query = mongoose.Query;
39
+ module.exports.Model = mongoose.Model;
40
+ module.exports.Document = mongoose.Document;
41
+ module.exports.ObjectId = mongoose.ObjectId;
42
+ module.exports.isValidObjectId = mongoose.isValidObjectId;
43
+ module.exports.isObjectIdOrHexString = mongoose.isObjectIdOrHexString;
44
+ module.exports.syncIndexes = mongoose.syncIndexes;
45
+ module.exports.Decimal128 = mongoose.Decimal128;
46
+ module.exports.Mixed = mongoose.Mixed;
47
+ module.exports.Date = mongoose.Date;
48
+ module.exports.Number = mongoose.Number;
49
+ module.exports.Error = mongoose.Error;
50
+ module.exports.MongooseError = mongoose.MongooseError;
51
+ module.exports.now = mongoose.now;
52
+ module.exports.CastError = mongoose.CastError;
53
+ module.exports.SchemaTypeOptions = mongoose.SchemaTypeOptions;
54
+ module.exports.mongo = mongoose.mongo;
55
+ module.exports.mquery = mongoose.mquery;
56
+ module.exports.sanitizeFilter = mongoose.sanitizeFilter;
57
+ module.exports.trusted = mongoose.trusted;
58
+ module.exports.skipMiddlewareFunction = mongoose.skipMiddlewareFunction;
59
+ module.exports.overwriteMiddlewareResult = mongoose.overwriteMiddlewareResult;
60
+
61
+ // The following properties are not exported using ESM because `setDriver()` can mutate these
62
+ // module.exports.connection = mongoose.connection;
63
+ // module.exports.Collection = mongoose.Collection;
64
+ // module.exports.Connection = mongoose.Connection;