@datanimbus/mongoose 9.13.1 → 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
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
8
+ const PopulateOptions = require('./options/populateOptions');
8
9
  const checkEmbeddedDiscriminatorKeyProjection =
9
10
  require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection');
10
11
  const get = require('./helpers/get');
@@ -12,41 +13,17 @@ const getDiscriminatorByValue =
12
13
  require('./helpers/discriminator/getDiscriminatorByValue');
13
14
  const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
14
15
  const isExclusive = require('./helpers/projection/isExclusive');
16
+ const isPOJO = require('./helpers/isPOJO');
15
17
  const clone = require('./helpers/clone');
16
- const utils = require('./utils');
17
-
18
- /**
19
- * Prepare a set of path options for query population.
20
- *
21
- * @param {Query} query
22
- * @param {Object} options
23
- * @return {Array}
24
- */
25
-
26
- exports.preparePopulationOptions = function preparePopulationOptions(query, options) {
27
- const _populate = query.options.populate;
28
- const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []);
29
-
30
- // lean options should trickle through all queries
31
- if (options.lean != null) {
32
- pop
33
- .filter(p => (p && p.options && p.options.lean) == null)
34
- .forEach(makeLean(options.lean));
35
- }
36
-
37
- pop.forEach(opts => {
38
- opts._localModel = query.model;
39
- });
40
-
41
- return pop;
42
- };
18
+ const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
19
+ const setInheritedReadOptions = require('./helpers/populate/setInheritedReadOptions');
43
20
 
44
21
  /**
45
22
  * Prepare a set of path options for query population. This is the MongooseQuery
46
23
  * version
47
24
  *
48
25
  * @param {Query} query
49
- * @param {Object} options
26
+ * @param {object} options
50
27
  * @return {Array}
51
28
  */
52
29
 
@@ -57,11 +34,11 @@ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query,
57
34
  // lean options should trickle through all queries
58
35
  if (options.lean != null) {
59
36
  pop
60
- .filter(p => (p && p.options && p.options.lean) == null)
37
+ .filter(p => p?.options?.lean == null)
61
38
  .forEach(makeLean(options.lean));
62
39
  }
63
40
 
64
- const session = query && query.options && query.options.session || null;
41
+ const session = query?.options?.session || null;
65
42
  if (session != null) {
66
43
  pop.forEach(path => {
67
44
  if (path.options == null) {
@@ -75,12 +52,19 @@ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query,
75
52
  }
76
53
 
77
54
  const projection = query._fieldsForExec();
78
- pop.forEach(p => {
79
- p._queryProjection = projection;
80
- });
81
- pop.forEach(opts => {
82
- opts._localModel = query.model;
83
- });
55
+ for (let i = 0; i < pop.length; ++i) {
56
+ if (pop[i] instanceof PopulateOptions) {
57
+ pop[i] = new PopulateOptions({
58
+ ...pop[i],
59
+ _queryProjection: projection,
60
+ _localModel: query.model
61
+ });
62
+ } else {
63
+ pop[i]._queryProjection = projection;
64
+ pop[i]._localModel = query.model;
65
+ }
66
+ }
67
+ setInheritedReadOptions(query, pop);
84
68
 
85
69
  return pop;
86
70
  };
@@ -90,8 +74,8 @@ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query,
90
74
  * it returns an instance of the given model.
91
75
  *
92
76
  * @param {Model} model
93
- * @param {Object} doc
94
- * @param {Object} fields
77
+ * @param {object} doc
78
+ * @param {object} fields
95
79
  *
96
80
  * @return {Document}
97
81
  */
@@ -101,28 +85,33 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
101
85
  model.schema.discriminatorMapping :
102
86
  null;
103
87
 
104
- const key = discriminatorMapping && discriminatorMapping.isRoot ?
88
+ const key = discriminatorMapping?.isRoot ?
105
89
  discriminatorMapping.key :
106
90
  null;
107
91
 
92
+ const _opts = {
93
+ skipId: true,
94
+ isNew: false,
95
+ willInit: true
96
+ };
97
+ if (options?.defaults != null) {
98
+ _opts.defaults = options.defaults;
99
+ }
100
+ if (options?.strict != null) {
101
+ _opts.strict = options.strict;
102
+ }
103
+
108
104
  const value = doc[key];
109
105
  if (key && value && model.discriminators) {
110
106
  const discriminator = getDiscriminatorByKey(model.discriminators, value) || getDiscriminatorByValue(model.discriminators, value);
111
107
  if (discriminator) {
112
108
  const _fields = clone(userProvidedFields);
113
109
  exports.applyPaths(_fields, discriminator.schema);
114
- return new discriminator(undefined, _fields, true);
110
+
111
+ return new discriminator(undefined, _fields, _opts);
115
112
  }
116
113
  }
117
114
 
118
- const _opts = {
119
- skipId: true,
120
- isNew: false,
121
- willInit: true
122
- };
123
- if (options != null && 'defaults' in options) {
124
- _opts.defaults = options.defaults;
125
- }
126
115
  return new model(undefined, fields, _opts);
127
116
  };
128
117
 
@@ -131,9 +120,13 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
131
120
  */
132
121
 
133
122
  exports.createModelAndInit = function createModelAndInit(model, doc, fields, userProvidedFields, options, populatedIds, callback) {
134
- const initOpts = populatedIds ?
135
- { populated: populatedIds } :
136
- undefined;
123
+ const initOpts = {};
124
+ if (populatedIds) {
125
+ initOpts.populated = populatedIds;
126
+ }
127
+ if (options?.middleware != null) {
128
+ initOpts.middleware = options.middleware;
129
+ }
137
130
 
138
131
  const casted = exports.createModel(model, doc, fields, userProvidedFields, options);
139
132
  try {
@@ -147,18 +140,44 @@ exports.createModelAndInit = function createModelAndInit(model, doc, fields, use
147
140
  * ignore
148
141
  */
149
142
 
150
- exports.applyPaths = function applyPaths(fields, schema) {
143
+ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
151
144
  // determine if query is selecting or excluding fields
152
145
  let exclude;
153
146
  let keys;
154
- let keyIndex;
147
+ const minusPathsToSkip = new Set();
155
148
 
156
149
  if (fields) {
150
+ // `+path` can't override schema-level `select: false` with `sanitizeProjection`. Also remove
151
+ // `-+path`, because collapsing minus paths below would turn it into `+path`.
152
+ if (sanitizeProjection) {
153
+ for (const key of Object.keys(fields)) {
154
+ if (key[0] === '+' || key.startsWith('-+')) {
155
+ delete fields[key];
156
+ }
157
+ }
158
+ }
159
+
157
160
  keys = Object.keys(fields);
158
- keyIndex = keys.length;
159
- let hasElemMatch = false;
160
161
 
161
- while (keyIndex--) {
162
+ // Collapse minus paths
163
+ const minusPaths = [];
164
+ for (let i = 0; i < keys.length; ++i) {
165
+ const key = keys[i];
166
+ if (keys[i][0] !== '-') {
167
+ continue;
168
+ }
169
+
170
+ delete fields[key];
171
+ if (key === '-_id') {
172
+ fields['_id'] = 0;
173
+ } else {
174
+ minusPaths.push(key.slice(1));
175
+ }
176
+ }
177
+
178
+ keys = Object.keys(fields);
179
+ let hasElemMatch = false;
180
+ for (let keyIndex = 0; keyIndex < keys.length; ++keyIndex) {
162
181
  if (keys[keyIndex][0] === '+') {
163
182
  continue;
164
183
  }
@@ -168,23 +187,23 @@ exports.applyPaths = function applyPaths(fields, schema) {
168
187
  continue;
169
188
  }
170
189
  // `$elemMatch` is inclusive on its own, but MongoDB treats `{ arr: { $elemMatch }, name: 0 }` as exclusive
171
- if (field != null && field.$elemMatch != null) {
190
+ if (field?.$elemMatch != null) {
172
191
  hasElemMatch = true;
173
192
  continue;
174
193
  }
175
- // `_id: 1, name: 0` is a mixed inclusive/exclusive projection in
176
- // MongoDB 4.0 and earlier, but not in later versions.
177
194
  if (keys[keyIndex] === '_id' && keys.length > 1) {
178
195
  continue;
179
196
  }
197
+ if (keys[keyIndex] === schema.options.discriminatorKey && keys.length > 1 && field != null && !field) {
198
+ continue;
199
+ }
180
200
  // Nested sub-projections like `{ profile: { bio: 0 } }` are exclusive or inclusive based on their
181
201
  // nested values, unlike expressions like `{ $concat: [...] }`, which are always inclusive
182
- if (utils.isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
183
- const nestedExclude = isExclusive(field);
184
- if (nestedExclude == null) {
202
+ if (isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
203
+ exclude = isExclusive(field) ?? undefined;
204
+ if (exclude === undefined) {
185
205
  continue;
186
206
  }
187
- exclude = nestedExclude;
188
207
  break;
189
208
  }
190
209
  exclude = !field;
@@ -193,32 +212,70 @@ exports.applyPaths = function applyPaths(fields, schema) {
193
212
  if (exclude === undefined && hasElemMatch) {
194
213
  exclude = false;
195
214
  }
215
+
216
+ // Potentially add back minus paths based on schema-level path config
217
+ // and whether the projection is inclusive
218
+ for (const path of minusPaths) {
219
+ const type = schema.path(path);
220
+ // If the path isn't selected by default or the projection is not
221
+ // inclusive, minus path is treated as equivalent to `key: 0`.
222
+ // But we also allow using `-name` to remove `name` from an inclusive
223
+ // projection if `name` has schema-level `select: true`.
224
+ if (!type?.selected || exclude !== false) {
225
+ fields[path] = 0;
226
+ exclude = true;
227
+ } else if (type?.selected && exclude === false) {
228
+ // Make a note of minus paths that are overwriting paths that are
229
+ // included by default.
230
+ minusPathsToSkip.add(path);
231
+ }
232
+ }
196
233
  }
197
234
 
198
235
  // if selecting, apply default schematype select:true fields
199
236
  // if excluding, apply schematype select:false fields
200
-
201
237
  const selected = [];
202
238
  const excluded = [];
203
239
  const stack = [];
204
240
 
205
- analyzeSchema(schema);
206
-
241
+ // Walking the schema is only necessary if the schema or one of its nested schemas
242
+ // has a schema-level `select`. `_hasSelectedPaths` is undefined if the schema
243
+ // hasn't been compiled.
244
+ if (schema._hasSelectedPaths !== false) {
245
+ analyzeSchema(schema);
246
+ }
247
+ // If `sanitizeProjection` removed every inclusion, the projection is now exclusive
248
+ if (sanitizeProjection && exclude === false) {
249
+ const keys = Object.keys(fields);
250
+ if (!keys.some(key => (key !== '_id' || keys.length === 1) && isDefiningProjection(fields[key]) && fields[key])) {
251
+ exclude = true;
252
+ }
253
+ }
207
254
  switch (exclude) {
208
255
  case true:
209
256
  for (const fieldName of excluded) {
257
+ // Skip if an ancestor path is already excluded in `fields` (for
258
+ // example the user did `.select('-subd')` and `subd.raw` has
259
+ // schema-level `select: false`) to avoid MongoDB's "Path collision"
260
+ // error from projecting both `subd` and `subd.raw`. See gh-12798
261
+ if (hasExcludedAncestor(fields, fieldName)) {
262
+ continue;
263
+ }
210
264
  fields[fieldName] = 0;
211
265
  }
212
266
  break;
213
267
  case false:
214
- if (schema &&
215
- schema.paths['_id'] &&
216
- schema.paths['_id'].options &&
217
- schema.paths['_id'].options.select === false) {
268
+ if (schema?.paths['_id']?.options?.select === false) {
218
269
  fields._id = 0;
219
270
  }
220
271
 
221
272
  for (const fieldName of selected) {
273
+ if (minusPathsToSkip.has(fieldName)) {
274
+ continue;
275
+ }
276
+ if (isPathSelectedInclusive(fields, fieldName)) {
277
+ continue;
278
+ }
222
279
  fields[fieldName] = fields[fieldName] || 1;
223
280
  }
224
281
  break;
@@ -261,7 +318,10 @@ exports.applyPaths = function applyPaths(fields, schema) {
261
318
  if (type.$isSchemaMap || path.endsWith('.$*')) {
262
319
  const plusPath = '+' + path;
263
320
  const hasPlusPath = fields && plusPath in fields;
264
- if (type.options && type.options.select === false && !hasPlusPath) {
321
+ if (type.options?.select === false && sanitizeProjection) {
322
+ removeInclusions(path);
323
+ excluded.push(path);
324
+ } else if (type.options?.select === false && !hasPlusPath) {
265
325
  excluded.push(path);
266
326
  }
267
327
  return;
@@ -269,7 +329,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
269
329
  let addedPath = analyzePath(path, type);
270
330
  // arrays
271
331
  if (addedPath == null && !Array.isArray(type) && type.$isMongooseArray && !type.$isMongooseDocumentArray) {
272
- addedPath = analyzePath(path, type.caster);
332
+ addedPath = analyzePath(path, type.embeddedSchemaType);
273
333
  }
274
334
  if (addedPath != null) {
275
335
  addedPaths.push(addedPath);
@@ -292,25 +352,38 @@ exports.applyPaths = function applyPaths(fields, schema) {
292
352
  }
293
353
 
294
354
  function analyzePath(path, type) {
295
- const plusPath = '+' + path;
296
- const hasPlusPath = fields && plusPath in fields;
297
- if (hasPlusPath) {
298
- // forced inclusion
299
- delete fields[plusPath];
355
+ if (fields == null) {
356
+ return;
300
357
  }
301
358
 
359
+ // If schema-level selected not set, nothing to do
302
360
  if (typeof type.selected !== 'boolean') {
303
361
  return;
304
362
  }
305
363
 
364
+ if (type.selected === false && sanitizeProjection) {
365
+ // Fall through so `path` is excluded
366
+ removeInclusions(path);
367
+ } else if (type.selected === false && fields[path]) {
368
+ // User overwriting default exclusion
369
+ return;
370
+ }
371
+
306
372
  // If set to 0, we're explicitly excluding the discriminator key. Can't do this for all fields,
307
373
  // because we have tests that assert that using `-path` to exclude schema-level `select: true`
308
374
  // fields counts as an exclusive projection. See gh-11546
309
- if (exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) {
375
+ if (!exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) {
376
+ delete fields[path];
377
+ return;
378
+ }
379
+
380
+ if (exclude === false && type.selected && fields[path] != null && !fields[path]) {
310
381
  delete fields[path];
311
382
  return;
312
383
  }
313
384
 
385
+ const plusPath = '+' + path;
386
+ const hasPlusPath = fields && plusPath in fields;
314
387
  if (hasPlusPath) {
315
388
  // forced inclusion
316
389
  delete fields[plusPath];
@@ -337,7 +410,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
337
410
  // Special case: if user has included a parent path of a discriminator key,
338
411
  // don't explicitly project in the discriminator key because that will
339
412
  // project out everything else under the parent path
340
- if (!exclude && (type && type.options && type.options.$skipDiscriminatorCheck || false)) {
413
+ if (!exclude && (type?.options?.$skipDiscriminatorCheck || false)) {
341
414
  let cur = '';
342
415
  for (let i = 0; i < pieces.length; ++i) {
343
416
  cur += (cur.length === 0 ? '' : '.') + pieces[i];
@@ -351,19 +424,49 @@ exports.applyPaths = function applyPaths(fields, schema) {
351
424
  (type.selected ? selected : excluded).push(path);
352
425
  return path;
353
426
  }
427
+
428
+ // With `sanitizeProjection`, remove anything other than an exclusion that would project in
429
+ // `path`: `path` itself, a parent like `profile` for `profile.ssn`, or a child path.
430
+ function removeInclusions(path) {
431
+ for (const key of Object.keys(fields)) {
432
+ if (isDefiningProjection(fields[key]) && !fields[key]) {
433
+ continue;
434
+ }
435
+ // Positional projections like `comments.$` project in the whole array element
436
+ const keyPath = key.endsWith('.$') ? key.slice(0, -2) : key;
437
+ if (keyPath === path || keyPath.startsWith(path + '.') || path.startsWith(keyPath + '.')) {
438
+ delete fields[key];
439
+ }
440
+ }
441
+ }
442
+
443
+ function hasExcludedAncestor(fields, path) {
444
+ let i = -1;
445
+ while ((i = path.indexOf('.', i + 1)) !== -1) {
446
+ const ancestor = fields[path.slice(0, i)];
447
+ // Any falsy defining value (`0`, `false`, `''`, `NaN`) excludes a
448
+ // path, matching how `exclude` itself is derived above (`!field`).
449
+ // `ancestor == null` means the key isn't present at all, which is
450
+ // not an exclusion. See gh-12798
451
+ if (ancestor != null && !ancestor) {
452
+ return true;
453
+ }
454
+ }
455
+ return false;
456
+ }
354
457
  };
355
458
 
356
459
  /**
357
460
  * Set each path query option to lean
358
461
  *
359
- * @param {Object} option
462
+ * @param {object} option
360
463
  */
361
464
 
362
465
  function makeLean(val) {
363
466
  return function(option) {
364
467
  option.options || (option.options = {});
365
468
 
366
- if (val != null && Array.isArray(val.virtuals)) {
469
+ if (Array.isArray(val?.virtuals)) {
367
470
  val = Object.assign({}, val);
368
471
  val.virtuals = val.virtuals.
369
472
  filter(path => typeof path === 'string' && path.startsWith(option.path + '.')).