@datanimbus/mongoose 6.13.10

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 (292) hide show
  1. package/.eslintrc.js +232 -0
  2. package/.mocharc.yml +4 -0
  3. package/LICENSE.md +22 -0
  4. package/README.md +387 -0
  5. package/SECURITY.md +1 -0
  6. package/browser.js +8 -0
  7. package/dist/browser.umd.js +2 -0
  8. package/index.js +63 -0
  9. package/lgtm.yml +12 -0
  10. package/lib/aggregate.js +1164 -0
  11. package/lib/browser.js +158 -0
  12. package/lib/browserDocument.js +101 -0
  13. package/lib/cast/boolean.js +32 -0
  14. package/lib/cast/date.js +41 -0
  15. package/lib/cast/decimal128.js +36 -0
  16. package/lib/cast/number.js +42 -0
  17. package/lib/cast/objectid.js +29 -0
  18. package/lib/cast/string.js +37 -0
  19. package/lib/cast.js +418 -0
  20. package/lib/collection.js +311 -0
  21. package/lib/connection.js +1574 -0
  22. package/lib/connectionstate.js +26 -0
  23. package/lib/cursor/AggregationCursor.js +380 -0
  24. package/lib/cursor/ChangeStream.js +154 -0
  25. package/lib/cursor/QueryCursor.js +538 -0
  26. package/lib/document.js +4771 -0
  27. package/lib/document_provider.js +30 -0
  28. package/lib/driver.js +15 -0
  29. package/lib/drivers/SPEC.md +4 -0
  30. package/lib/drivers/browser/ReadPreference.js +7 -0
  31. package/lib/drivers/browser/binary.js +14 -0
  32. package/lib/drivers/browser/decimal128.js +7 -0
  33. package/lib/drivers/browser/index.js +16 -0
  34. package/lib/drivers/browser/objectid.js +29 -0
  35. package/lib/drivers/node-mongodb-native/ReadPreference.js +47 -0
  36. package/lib/drivers/node-mongodb-native/binary.js +10 -0
  37. package/lib/drivers/node-mongodb-native/collection.js +460 -0
  38. package/lib/drivers/node-mongodb-native/connection.js +166 -0
  39. package/lib/drivers/node-mongodb-native/decimal128.js +7 -0
  40. package/lib/drivers/node-mongodb-native/index.js +12 -0
  41. package/lib/drivers/node-mongodb-native/objectid.js +16 -0
  42. package/lib/error/browserMissingSchema.js +28 -0
  43. package/lib/error/bulkWriteError.js +41 -0
  44. package/lib/error/cast.js +158 -0
  45. package/lib/error/disconnected.js +33 -0
  46. package/lib/error/divergentArray.js +38 -0
  47. package/lib/error/eachAsyncMultiError.js +41 -0
  48. package/lib/error/index.js +228 -0
  49. package/lib/error/messages.js +47 -0
  50. package/lib/error/missingSchema.js +31 -0
  51. package/lib/error/mongooseError.js +13 -0
  52. package/lib/error/notFound.js +45 -0
  53. package/lib/error/objectExpected.js +30 -0
  54. package/lib/error/objectParameter.js +30 -0
  55. package/lib/error/overwriteModel.js +30 -0
  56. package/lib/error/parallelSave.js +30 -0
  57. package/lib/error/parallelValidate.js +31 -0
  58. package/lib/error/serverSelection.js +61 -0
  59. package/lib/error/setOptionError.js +101 -0
  60. package/lib/error/strict.js +33 -0
  61. package/lib/error/strictPopulate.js +29 -0
  62. package/lib/error/syncIndexes.js +30 -0
  63. package/lib/error/validation.js +103 -0
  64. package/lib/error/validator.js +99 -0
  65. package/lib/error/version.js +36 -0
  66. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +39 -0
  67. package/lib/helpers/aggregate/stringifyFunctionOperators.js +50 -0
  68. package/lib/helpers/arrayDepth.js +33 -0
  69. package/lib/helpers/clone.js +177 -0
  70. package/lib/helpers/common.js +127 -0
  71. package/lib/helpers/cursor/eachAsync.js +222 -0
  72. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +16 -0
  73. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +12 -0
  74. package/lib/helpers/discriminator/getConstructor.js +26 -0
  75. package/lib/helpers/discriminator/getDiscriminatorByValue.js +28 -0
  76. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +27 -0
  77. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +64 -0
  78. package/lib/helpers/document/applyDefaults.js +128 -0
  79. package/lib/helpers/document/cleanModifiedSubpaths.js +35 -0
  80. package/lib/helpers/document/compile.js +237 -0
  81. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +50 -0
  82. package/lib/helpers/document/handleSpreadDoc.js +35 -0
  83. package/lib/helpers/each.js +25 -0
  84. package/lib/helpers/error/combinePathErrors.js +22 -0
  85. package/lib/helpers/firstKey.js +8 -0
  86. package/lib/helpers/get.js +65 -0
  87. package/lib/helpers/getConstructorName.js +16 -0
  88. package/lib/helpers/getDefaultBulkwriteResult.js +27 -0
  89. package/lib/helpers/getFunctionName.js +10 -0
  90. package/lib/helpers/immediate.js +16 -0
  91. package/lib/helpers/indexes/applySchemaCollation.js +13 -0
  92. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +14 -0
  93. package/lib/helpers/indexes/getRelatedIndexes.js +59 -0
  94. package/lib/helpers/indexes/isDefaultIdIndex.js +18 -0
  95. package/lib/helpers/indexes/isIndexEqual.js +96 -0
  96. package/lib/helpers/indexes/isTextIndex.js +16 -0
  97. package/lib/helpers/isAsyncFunction.js +9 -0
  98. package/lib/helpers/isBsonType.js +16 -0
  99. package/lib/helpers/isMongooseObject.js +22 -0
  100. package/lib/helpers/isObject.js +16 -0
  101. package/lib/helpers/isPromise.js +6 -0
  102. package/lib/helpers/isSimpleValidator.js +22 -0
  103. package/lib/helpers/model/applyDefaultsToPOJO.js +52 -0
  104. package/lib/helpers/model/applyHooks.js +149 -0
  105. package/lib/helpers/model/applyMethods.js +70 -0
  106. package/lib/helpers/model/applyStaticHooks.js +71 -0
  107. package/lib/helpers/model/applyStatics.js +13 -0
  108. package/lib/helpers/model/castBulkWrite.js +240 -0
  109. package/lib/helpers/model/discriminator.js +218 -0
  110. package/lib/helpers/model/pushNestedArrayPaths.js +15 -0
  111. package/lib/helpers/once.js +12 -0
  112. package/lib/helpers/parallelLimit.js +55 -0
  113. package/lib/helpers/path/parentPaths.js +18 -0
  114. package/lib/helpers/path/setDottedPath.js +33 -0
  115. package/lib/helpers/pluralize.js +94 -0
  116. package/lib/helpers/populate/SkipPopulateValue.js +10 -0
  117. package/lib/helpers/populate/assignRawDocsToIdStructure.js +124 -0
  118. package/lib/helpers/populate/assignVals.js +337 -0
  119. package/lib/helpers/populate/createPopulateQueryFilter.js +97 -0
  120. package/lib/helpers/populate/getModelsMapForPopulate.js +756 -0
  121. package/lib/helpers/populate/getSchemaTypes.js +233 -0
  122. package/lib/helpers/populate/getVirtual.js +72 -0
  123. package/lib/helpers/populate/leanPopulateMap.js +7 -0
  124. package/lib/helpers/populate/lookupLocalFields.js +40 -0
  125. package/lib/helpers/populate/markArraySubdocsPopulated.js +47 -0
  126. package/lib/helpers/populate/modelNamesFromRefPath.js +68 -0
  127. package/lib/helpers/populate/removeDeselectedForeignField.js +31 -0
  128. package/lib/helpers/populate/validateRef.js +19 -0
  129. package/lib/helpers/printJestWarning.js +21 -0
  130. package/lib/helpers/printStrictQueryWarning.js +11 -0
  131. package/lib/helpers/processConnectionOptions.js +65 -0
  132. package/lib/helpers/projection/applyProjection.js +77 -0
  133. package/lib/helpers/projection/hasIncludedChildren.js +41 -0
  134. package/lib/helpers/projection/isDefiningProjection.js +18 -0
  135. package/lib/helpers/projection/isExclusive.js +35 -0
  136. package/lib/helpers/projection/isInclusive.js +38 -0
  137. package/lib/helpers/projection/isNestedProjection.js +8 -0
  138. package/lib/helpers/projection/isPathExcluded.js +40 -0
  139. package/lib/helpers/projection/isPathSelectedInclusive.js +28 -0
  140. package/lib/helpers/projection/isSubpath.js +14 -0
  141. package/lib/helpers/projection/parseProjection.js +33 -0
  142. package/lib/helpers/promiseOrCallback.js +55 -0
  143. package/lib/helpers/query/applyGlobalOption.js +29 -0
  144. package/lib/helpers/query/applyQueryMiddleware.js +79 -0
  145. package/lib/helpers/query/cast$expr.js +282 -0
  146. package/lib/helpers/query/castFilterPath.js +54 -0
  147. package/lib/helpers/query/castUpdate.js +560 -0
  148. package/lib/helpers/query/completeMany.js +52 -0
  149. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +90 -0
  150. package/lib/helpers/query/handleImmutable.js +28 -0
  151. package/lib/helpers/query/hasDollarKeys.js +23 -0
  152. package/lib/helpers/query/isOperator.js +14 -0
  153. package/lib/helpers/query/sanitizeFilter.js +38 -0
  154. package/lib/helpers/query/sanitizeProjection.js +14 -0
  155. package/lib/helpers/query/selectPopulatedFields.js +49 -0
  156. package/lib/helpers/query/trusted.js +13 -0
  157. package/lib/helpers/query/validOps.js +24 -0
  158. package/lib/helpers/query/wrapThunk.js +31 -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/applyWriteConcern.js +30 -0
  163. package/lib/helpers/schema/cleanPositionalOperators.js +12 -0
  164. package/lib/helpers/schema/getIndexes.js +164 -0
  165. package/lib/helpers/schema/getKeysInSchemaOrder.js +28 -0
  166. package/lib/helpers/schema/getPath.js +37 -0
  167. package/lib/helpers/schema/handleIdOption.js +20 -0
  168. package/lib/helpers/schema/handleTimestampOption.js +24 -0
  169. package/lib/helpers/schema/idGetter.js +32 -0
  170. package/lib/helpers/schema/merge.js +28 -0
  171. package/lib/helpers/schematype/handleImmutable.js +50 -0
  172. package/lib/helpers/setDefaultsOnInsert.js +132 -0
  173. package/lib/helpers/specialProperties.js +3 -0
  174. package/lib/helpers/symbols.js +20 -0
  175. package/lib/helpers/timers.js +3 -0
  176. package/lib/helpers/timestamps/setDocumentTimestamps.js +26 -0
  177. package/lib/helpers/timestamps/setupTimestamps.js +101 -0
  178. package/lib/helpers/topology/allServersUnknown.js +12 -0
  179. package/lib/helpers/topology/isAtlas.js +31 -0
  180. package/lib/helpers/topology/isSSLError.js +16 -0
  181. package/lib/helpers/update/applyTimestampsToChildren.js +193 -0
  182. package/lib/helpers/update/applyTimestampsToUpdate.js +117 -0
  183. package/lib/helpers/update/castArrayFilters.js +109 -0
  184. package/lib/helpers/update/modifiedPaths.js +33 -0
  185. package/lib/helpers/update/moveImmutableProperties.js +53 -0
  186. package/lib/helpers/update/removeUnusedArrayFilters.js +32 -0
  187. package/lib/helpers/update/updatedPathsByArrayFilter.js +27 -0
  188. package/lib/helpers/updateValidators.js +249 -0
  189. package/lib/index.js +1338 -0
  190. package/lib/internal.js +46 -0
  191. package/lib/model.js +5474 -0
  192. package/lib/options/PopulateOptions.js +36 -0
  193. package/lib/options/SchemaArrayOptions.js +78 -0
  194. package/lib/options/SchemaBufferOptions.js +38 -0
  195. package/lib/options/SchemaDateOptions.js +71 -0
  196. package/lib/options/SchemaDocumentArrayOptions.js +68 -0
  197. package/lib/options/SchemaMapOptions.js +43 -0
  198. package/lib/options/SchemaNumberOptions.js +101 -0
  199. package/lib/options/SchemaObjectIdOptions.js +64 -0
  200. package/lib/options/SchemaStringOptions.js +138 -0
  201. package/lib/options/SchemaSubdocumentOptions.js +42 -0
  202. package/lib/options/SchemaTypeOptions.js +244 -0
  203. package/lib/options/VirtualOptions.js +164 -0
  204. package/lib/options/propertyOptions.js +8 -0
  205. package/lib/options/removeOptions.js +14 -0
  206. package/lib/options/saveOptions.js +14 -0
  207. package/lib/options.js +15 -0
  208. package/lib/plugins/index.js +7 -0
  209. package/lib/plugins/removeSubdocs.js +31 -0
  210. package/lib/plugins/saveSubdocs.js +66 -0
  211. package/lib/plugins/sharding.js +83 -0
  212. package/lib/plugins/trackTransaction.js +92 -0
  213. package/lib/plugins/validateBeforeSave.js +45 -0
  214. package/lib/promise_provider.js +49 -0
  215. package/lib/query.js +5982 -0
  216. package/lib/queryhelpers.js +353 -0
  217. package/lib/schema/DocumentArrayElement.js +100 -0
  218. package/lib/schema/SubdocumentPath.js +369 -0
  219. package/lib/schema/array.js +663 -0
  220. package/lib/schema/boolean.js +267 -0
  221. package/lib/schema/buffer.js +269 -0
  222. package/lib/schema/date.js +404 -0
  223. package/lib/schema/decimal128.js +210 -0
  224. package/lib/schema/documentarray.js +598 -0
  225. package/lib/schema/index.js +39 -0
  226. package/lib/schema/map.js +84 -0
  227. package/lib/schema/mixed.js +132 -0
  228. package/lib/schema/number.js +438 -0
  229. package/lib/schema/objectid.js +295 -0
  230. package/lib/schema/operators/bitwise.js +38 -0
  231. package/lib/schema/operators/exists.js +12 -0
  232. package/lib/schema/operators/geospatial.js +107 -0
  233. package/lib/schema/operators/helpers.js +32 -0
  234. package/lib/schema/operators/text.js +39 -0
  235. package/lib/schema/operators/type.js +20 -0
  236. package/lib/schema/string.js +694 -0
  237. package/lib/schema/symbols.js +5 -0
  238. package/lib/schema/uuid.js +334 -0
  239. package/lib/schema.js +2665 -0
  240. package/lib/schematype.js +1727 -0
  241. package/lib/statemachine.js +207 -0
  242. package/lib/types/ArraySubdocument.js +189 -0
  243. package/lib/types/DocumentArray/index.js +113 -0
  244. package/lib/types/DocumentArray/isMongooseDocumentArray.js +5 -0
  245. package/lib/types/DocumentArray/methods/index.js +383 -0
  246. package/lib/types/array/index.js +116 -0
  247. package/lib/types/array/isMongooseArray.js +5 -0
  248. package/lib/types/array/methods/index.js +1014 -0
  249. package/lib/types/buffer.js +277 -0
  250. package/lib/types/decimal128.js +13 -0
  251. package/lib/types/index.js +20 -0
  252. package/lib/types/map.js +354 -0
  253. package/lib/types/objectid.js +41 -0
  254. package/lib/types/subdocument.js +432 -0
  255. package/lib/utils.js +1011 -0
  256. package/lib/validoptions.js +36 -0
  257. package/lib/virtualtype.js +175 -0
  258. package/package.json +164 -0
  259. package/scripts/build-browser.js +18 -0
  260. package/scripts/create-tarball.js +7 -0
  261. package/scripts/generateSearch.js +154 -0
  262. package/scripts/tsc-diagnostics-check.js +15 -0
  263. package/tools/auth.js +31 -0
  264. package/tools/repl.js +35 -0
  265. package/tools/sharded.js +46 -0
  266. package/tsconfig.json +9 -0
  267. package/types/aggregate.d.ts +174 -0
  268. package/types/augmentations.d.ts +9 -0
  269. package/types/callback.d.ts +8 -0
  270. package/types/collection.d.ts +44 -0
  271. package/types/connection.d.ts +242 -0
  272. package/types/cursor.d.ts +62 -0
  273. package/types/document.d.ts +266 -0
  274. package/types/error.d.ts +138 -0
  275. package/types/expressions.d.ts +2936 -0
  276. package/types/helpers.d.ts +32 -0
  277. package/types/index.d.ts +627 -0
  278. package/types/indexes.d.ts +98 -0
  279. package/types/inferschematype.d.ts +228 -0
  280. package/types/middlewares.d.ts +32 -0
  281. package/types/models.d.ts +488 -0
  282. package/types/mongooseoptions.d.ts +206 -0
  283. package/types/pipelinestage.d.ts +297 -0
  284. package/types/populate.d.ts +45 -0
  285. package/types/query.d.ts +659 -0
  286. package/types/schemaoptions.d.ts +231 -0
  287. package/types/schematypes.d.ts +478 -0
  288. package/types/session.d.ts +36 -0
  289. package/types/types.d.ts +104 -0
  290. package/types/utility.d.ts +43 -0
  291. package/types/validation.d.ts +34 -0
  292. package/types/virtuals.d.ts +14 -0
package/lib/schema.js ADDED
@@ -0,0 +1,2665 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const EventEmitter = require('events').EventEmitter;
8
+ const Kareem = require('kareem');
9
+ const MongooseError = require('./error/mongooseError');
10
+ const SchemaType = require('./schematype');
11
+ const SchemaTypeOptions = require('./options/SchemaTypeOptions');
12
+ const VirtualOptions = require('./options/VirtualOptions');
13
+ const VirtualType = require('./virtualtype');
14
+ const addAutoId = require('./helpers/schema/addAutoId');
15
+ const get = require('./helpers/get');
16
+ const getConstructorName = require('./helpers/getConstructorName');
17
+ const getIndexes = require('./helpers/schema/getIndexes');
18
+ const idGetter = require('./helpers/schema/idGetter');
19
+ const merge = require('./helpers/schema/merge');
20
+ const mpath = require('mpath');
21
+ const readPref = require('./driver').get().ReadPreference;
22
+ const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
23
+ const utils = require('./utils');
24
+ const validateRef = require('./helpers/populate/validateRef');
25
+ const util = require('util');
26
+
27
+ const hasNumericSubpathRegex = /\.\d+(\.|$)/;
28
+
29
+ let MongooseTypes;
30
+
31
+ const queryHooks = require('./helpers/query/applyQueryMiddleware').
32
+ middlewareFunctions;
33
+ const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
34
+ const hookNames = queryHooks.concat(documentHooks).
35
+ reduce((s, hook) => s.add(hook), new Set());
36
+
37
+ const isPOJO = utils.isPOJO;
38
+
39
+ let id = 0;
40
+
41
+ /**
42
+ * Schema constructor.
43
+ *
44
+ * #### Example:
45
+ *
46
+ * const child = new Schema({ name: String });
47
+ * const schema = new Schema({ name: String, age: Number, children: [child] });
48
+ * const Tree = mongoose.model('Tree', schema);
49
+ *
50
+ * // setting schema options
51
+ * new Schema({ name: String }, { _id: false, autoIndex: false })
52
+ *
53
+ * #### Options:
54
+ *
55
+ * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
56
+ * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
57
+ * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
58
+ * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
59
+ * - [capped](/docs/guide.html#capped): bool | number | object - defaults to false
60
+ * - [collection](/docs/guide.html#collection): string - no default
61
+ * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t`
62
+ * - [id](/docs/guide.html#id): bool - defaults to true
63
+ * - [_id](/docs/guide.html#_id): bool - defaults to true
64
+ * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
65
+ * - [read](/docs/guide.html#read): string
66
+ * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://www.mongodb.com/docs/manual/reference/write-concern/)
67
+ * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null`
68
+ * - [strict](/docs/guide.html#strict): bool - defaults to true
69
+ * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false
70
+ * - [toJSON](/docs/guide.html#toJSON) - object - no default
71
+ * - [toObject](/docs/guide.html#toObject) - object - no default
72
+ * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
73
+ * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
74
+ * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v"
75
+ * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html).
76
+ * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
77
+ * - [timeseries](/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection)
78
+ * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
79
+ * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
80
+ * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
81
+ * - [pluginTags](/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag.
82
+ *
83
+ * #### Options for Nested Schemas:
84
+ *
85
+ * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths.
86
+ *
87
+ * #### Note:
88
+ *
89
+ * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
90
+ *
91
+ * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
92
+ * @param {Object} [options]
93
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
94
+ * @event `init`: Emitted after the schema is compiled into a `Model`.
95
+ * @api public
96
+ */
97
+
98
+ function Schema(obj, options) {
99
+ if (!(this instanceof Schema)) {
100
+ return new Schema(obj, options);
101
+ }
102
+
103
+ this.obj = obj;
104
+ this.paths = {};
105
+ this.aliases = {};
106
+ this.subpaths = {};
107
+ this.virtuals = {};
108
+ this.singleNestedPaths = {};
109
+ this.nested = {};
110
+ this.inherits = {};
111
+ this.callQueue = [];
112
+ this._indexes = [];
113
+ this.methods = (options && options.methods) || {};
114
+ this.methodOptions = {};
115
+ this.statics = (options && options.statics) || {};
116
+ this.tree = {};
117
+ this.query = (options && options.query) || {};
118
+ this.childSchemas = [];
119
+ this.plugins = [];
120
+ // For internal debugging. Do not use this to try to save a schema in MDB.
121
+ this.$id = ++id;
122
+ this.mapPaths = [];
123
+
124
+ this.s = {
125
+ hooks: new Kareem()
126
+ };
127
+ this.options = this.defaultOptions(options);
128
+
129
+ // build paths
130
+ if (Array.isArray(obj)) {
131
+ for (const definition of obj) {
132
+ this.add(definition);
133
+ }
134
+ } else if (obj) {
135
+ this.add(obj);
136
+ }
137
+
138
+ // build virtual paths
139
+ if (options && options.virtuals) {
140
+ const virtuals = options.virtuals;
141
+ const pathNames = Object.keys(virtuals);
142
+ for (const pathName of pathNames) {
143
+ const pathOptions = virtuals[pathName].options ? virtuals[pathName].options : undefined;
144
+ const virtual = this.virtual(pathName, pathOptions);
145
+
146
+ if (virtuals[pathName].get) {
147
+ virtual.get(virtuals[pathName].get);
148
+ }
149
+
150
+ if (virtuals[pathName].set) {
151
+ virtual.set(virtuals[pathName].set);
152
+ }
153
+ }
154
+ }
155
+
156
+ // check if _id's value is a subdocument (gh-2276)
157
+ const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
158
+
159
+ // ensure the documents get an auto _id unless disabled
160
+ const auto_id = !this.paths['_id'] &&
161
+ (this.options._id) && !_idSubDoc;
162
+
163
+ if (auto_id) {
164
+ addAutoId(this);
165
+ }
166
+
167
+ this.setupTimestamp(this.options.timestamps);
168
+ }
169
+
170
+ /**
171
+ * Create virtual properties with alias field
172
+ * @api private
173
+ */
174
+ function aliasFields(schema, paths) {
175
+ for (const path of Object.keys(paths)) {
176
+ let alias = null;
177
+ if (paths[path] != null) {
178
+ alias = paths[path];
179
+ } else {
180
+ const options = get(schema.paths[path], 'options');
181
+ if (options == null) {
182
+ continue;
183
+ }
184
+
185
+ alias = options.alias;
186
+ }
187
+
188
+ if (!alias) {
189
+ continue;
190
+ }
191
+
192
+ const prop = schema.paths[path].path;
193
+ if (Array.isArray(alias)) {
194
+ for (const a of alias) {
195
+ if (typeof a !== 'string') {
196
+ throw new Error('Invalid value for alias option on ' + prop + ', got ' + a);
197
+ }
198
+
199
+ schema.aliases[a] = prop;
200
+
201
+ schema.
202
+ virtual(a).
203
+ get((function(p) {
204
+ return function() {
205
+ if (typeof this.get === 'function') {
206
+ return this.get(p);
207
+ }
208
+ return this[p];
209
+ };
210
+ })(prop)).
211
+ set((function(p) {
212
+ return function(v) {
213
+ return this.$set(p, v);
214
+ };
215
+ })(prop));
216
+ }
217
+
218
+ continue;
219
+ }
220
+
221
+ if (typeof alias !== 'string') {
222
+ throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
223
+ }
224
+
225
+ schema.aliases[alias] = prop;
226
+
227
+ schema.
228
+ virtual(alias).
229
+ get((function(p) {
230
+ return function() {
231
+ if (typeof this.get === 'function') {
232
+ return this.get(p);
233
+ }
234
+ return this[p];
235
+ };
236
+ })(prop)).
237
+ set((function(p) {
238
+ return function(v) {
239
+ return this.$set(p, v);
240
+ };
241
+ })(prop));
242
+ }
243
+ }
244
+
245
+ /*!
246
+ * Inherit from EventEmitter.
247
+ */
248
+ Schema.prototype = Object.create(EventEmitter.prototype);
249
+ Schema.prototype.constructor = Schema;
250
+ Schema.prototype.instanceOfSchema = true;
251
+
252
+ /*!
253
+ * ignore
254
+ */
255
+
256
+ Object.defineProperty(Schema.prototype, '$schemaType', {
257
+ configurable: false,
258
+ enumerable: false,
259
+ writable: true
260
+ });
261
+
262
+ /**
263
+ * Array of child schemas (from document arrays and single nested subdocs)
264
+ * and their corresponding compiled models. Each element of the array is
265
+ * an object with 2 properties: `schema` and `model`.
266
+ *
267
+ * This property is typically only useful for plugin authors and advanced users.
268
+ * You do not need to interact with this property at all to use mongoose.
269
+ *
270
+ * @api public
271
+ * @property childSchemas
272
+ * @memberOf Schema
273
+ * @instance
274
+ */
275
+
276
+ Object.defineProperty(Schema.prototype, 'childSchemas', {
277
+ configurable: false,
278
+ enumerable: true,
279
+ writable: true
280
+ });
281
+
282
+ /**
283
+ * Object containing all virtuals defined on this schema.
284
+ * The objects' keys are the virtual paths and values are instances of `VirtualType`.
285
+ *
286
+ * This property is typically only useful for plugin authors and advanced users.
287
+ * You do not need to interact with this property at all to use mongoose.
288
+ *
289
+ * #### Example:
290
+ *
291
+ * const schema = new Schema({});
292
+ * schema.virtual('answer').get(() => 42);
293
+ *
294
+ * console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
295
+ * console.log(schema.virtuals['answer'].getters[0].call()); // 42
296
+ *
297
+ * @api public
298
+ * @property virtuals
299
+ * @memberOf Schema
300
+ * @instance
301
+ */
302
+
303
+ Object.defineProperty(Schema.prototype, 'virtuals', {
304
+ configurable: false,
305
+ enumerable: true,
306
+ writable: true
307
+ });
308
+
309
+ /**
310
+ * The original object passed to the schema constructor
311
+ *
312
+ * #### Example:
313
+ *
314
+ * const schema = new Schema({ a: String }).add({ b: String });
315
+ * schema.obj; // { a: String }
316
+ *
317
+ * @api public
318
+ * @property obj
319
+ * @memberOf Schema
320
+ * @instance
321
+ */
322
+
323
+ Schema.prototype.obj;
324
+
325
+ /**
326
+ * The paths defined on this schema. The keys are the top-level paths
327
+ * in this schema, and the values are instances of the SchemaType class.
328
+ *
329
+ * #### Example:
330
+ *
331
+ * const schema = new Schema({ name: String }, { _id: false });
332
+ * schema.paths; // { name: SchemaString { ... } }
333
+ *
334
+ * schema.add({ age: Number });
335
+ * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
336
+ *
337
+ * @api public
338
+ * @property paths
339
+ * @memberOf Schema
340
+ * @instance
341
+ */
342
+
343
+ Schema.prototype.paths;
344
+
345
+ /**
346
+ * Schema as a tree
347
+ *
348
+ * #### Example:
349
+ *
350
+ * {
351
+ * '_id' : ObjectId
352
+ * , 'nested' : {
353
+ * 'key' : String
354
+ * }
355
+ * }
356
+ *
357
+ * @api private
358
+ * @property tree
359
+ * @memberOf Schema
360
+ * @instance
361
+ */
362
+
363
+ Schema.prototype.tree;
364
+
365
+ /**
366
+ * Returns a deep copy of the schema
367
+ *
368
+ * #### Example:
369
+ *
370
+ * const schema = new Schema({ name: String });
371
+ * const clone = schema.clone();
372
+ * clone === schema; // false
373
+ * clone.path('name'); // SchemaString { ... }
374
+ *
375
+ * @return {Schema} the cloned schema
376
+ * @api public
377
+ * @memberOf Schema
378
+ * @instance
379
+ */
380
+
381
+ Schema.prototype.clone = function() {
382
+ const s = this._clone();
383
+
384
+ // Bubble up `init` for backwards compat
385
+ s.on('init', v => this.emit('init', v));
386
+
387
+ return s;
388
+ };
389
+
390
+ /*!
391
+ * ignore
392
+ */
393
+
394
+ Schema.prototype._clone = function _clone(Constructor) {
395
+ Constructor = Constructor || (this.base == null ? Schema : this.base.Schema);
396
+
397
+ const s = new Constructor({}, this._userProvidedOptions);
398
+ s.base = this.base;
399
+ s.obj = this.obj;
400
+ s.options = utils.clone(this.options);
401
+ s.callQueue = this.callQueue.map(function(f) { return f; });
402
+ s.methods = utils.clone(this.methods);
403
+ s.methodOptions = utils.clone(this.methodOptions);
404
+ s.statics = utils.clone(this.statics);
405
+ s.query = utils.clone(this.query);
406
+ s.plugins = Array.prototype.slice.call(this.plugins);
407
+ s._indexes = utils.clone(this._indexes);
408
+ s.s.hooks = this.s.hooks.clone();
409
+
410
+ s.tree = utils.clone(this.tree);
411
+ s.paths = utils.clone(this.paths);
412
+ s.nested = utils.clone(this.nested);
413
+ s.subpaths = utils.clone(this.subpaths);
414
+ for (const schemaType of Object.values(s.paths)) {
415
+ if (schemaType.$isSingleNested) {
416
+ const path = schemaType.path;
417
+ for (const key of Object.keys(schemaType.schema.paths)) {
418
+ s.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
419
+ }
420
+ for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
421
+ s.singleNestedPaths[path + '.' + key] =
422
+ schemaType.schema.singleNestedPaths[key];
423
+ }
424
+ for (const key of Object.keys(schemaType.schema.subpaths)) {
425
+ s.singleNestedPaths[path + '.' + key] =
426
+ schemaType.schema.subpaths[key];
427
+ }
428
+ for (const key of Object.keys(schemaType.schema.nested)) {
429
+ s.singleNestedPaths[path + '.' + key] = 'nested';
430
+ }
431
+ }
432
+ }
433
+ s.childSchemas = gatherChildSchemas(s);
434
+
435
+ s.virtuals = utils.clone(this.virtuals);
436
+ s.$globalPluginsApplied = this.$globalPluginsApplied;
437
+ s.$isRootDiscriminator = this.$isRootDiscriminator;
438
+ s.$implicitlyCreated = this.$implicitlyCreated;
439
+ s.$id = ++id;
440
+ s.$originalSchemaId = this.$id;
441
+ s.mapPaths = [].concat(this.mapPaths);
442
+
443
+ if (this.discriminatorMapping != null) {
444
+ s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
445
+ }
446
+ if (this.discriminators != null) {
447
+ s.discriminators = Object.assign({}, this.discriminators);
448
+ }
449
+ if (this._applyDiscriminators != null) {
450
+ s._applyDiscriminators = Object.assign({}, this._applyDiscriminators);
451
+ }
452
+
453
+ s.aliases = Object.assign({}, this.aliases);
454
+
455
+ return s;
456
+ };
457
+
458
+ /**
459
+ * Returns a new schema that has the picked `paths` from this schema.
460
+ *
461
+ * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas.
462
+ *
463
+ * #### Example:
464
+ *
465
+ * const schema = Schema({ name: String, age: Number });
466
+ * // Creates a new schema with the same `name` path as `schema`,
467
+ * // but no `age` path.
468
+ * const newSchema = schema.pick(['name']);
469
+ *
470
+ * newSchema.path('name'); // SchemaString { ... }
471
+ * newSchema.path('age'); // undefined
472
+ *
473
+ * @param {String[]} paths List of Paths to pick for the new Schema
474
+ * @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
475
+ * @return {Schema}
476
+ * @api public
477
+ */
478
+
479
+ Schema.prototype.pick = function(paths, options) {
480
+ const newSchema = new Schema({}, options || this.options);
481
+ if (!Array.isArray(paths)) {
482
+ throw new MongooseError('Schema#pick() only accepts an array argument, ' +
483
+ 'got "' + typeof paths + '"');
484
+ }
485
+
486
+ for (const path of paths) {
487
+ if (this.nested[path]) {
488
+ newSchema.add({ [path]: get(this.tree, path) });
489
+ } else {
490
+ const schematype = this.path(path);
491
+ if (schematype == null) {
492
+ throw new MongooseError('Path `' + path + '` is not in the schema');
493
+ }
494
+ newSchema.add({ [path]: schematype });
495
+ }
496
+ }
497
+
498
+ return newSchema;
499
+ };
500
+
501
+ /**
502
+ * Returns a new schema that has the `paths` from the original schema, minus the omitted ones.
503
+ *
504
+ * This method is analagous to [Lodash's `omit()` function](https://lodash.com/docs/#omit) for Mongoose schemas.
505
+ *
506
+ * #### Example:
507
+ *
508
+ * const schema = Schema({ name: String, age: Number });
509
+ * // Creates a new schema omitting the `age` path
510
+ * const newSchema = schema.omit(['age']);
511
+ *
512
+ * newSchema.path('name'); // SchemaString { ... }
513
+ * newSchema.path('age'); // undefined
514
+ *
515
+ * @param {String[]} paths List of Paths to omit for the new Schema
516
+ * @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
517
+ * @return {Schema}
518
+ * @api public
519
+ */
520
+
521
+ Schema.prototype.omit = function(paths, options) {
522
+ const newSchema = new Schema(this, options || this.options);
523
+ if (!Array.isArray(paths)) {
524
+ throw new MongooseError(
525
+ 'Schema#omit() only accepts an array argument, ' +
526
+ 'got "' +
527
+ typeof paths +
528
+ '"'
529
+ );
530
+ }
531
+
532
+ newSchema.remove(paths);
533
+
534
+ for (const nested in newSchema.singleNestedPaths) {
535
+ if (paths.includes(nested)) {
536
+ delete newSchema.singleNestedPaths[nested];
537
+ }
538
+ }
539
+
540
+ return newSchema;
541
+ };
542
+
543
+ /**
544
+ * Returns default options for this schema, merged with `options`.
545
+ *
546
+ * @param {Object} [options] Options to overwrite the default options
547
+ * @return {Object} The merged options of `options` and the default options
548
+ * @api private
549
+ */
550
+
551
+ Schema.prototype.defaultOptions = function(options) {
552
+ this._userProvidedOptions = options == null ? {} : utils.clone(options);
553
+ const baseOptions = this.base && this.base.options || {};
554
+ const strict = 'strict' in baseOptions ? baseOptions.strict : true;
555
+ const id = 'id' in baseOptions ? baseOptions.id : true;
556
+ options = utils.options({
557
+ strict: strict,
558
+ strictQuery: 'strict' in this._userProvidedOptions ?
559
+ this._userProvidedOptions.strict :
560
+ 'strictQuery' in baseOptions ?
561
+ baseOptions.strictQuery : strict,
562
+ bufferCommands: true,
563
+ capped: false, // { size, max, autoIndexId }
564
+ versionKey: '__v',
565
+ optimisticConcurrency: false,
566
+ minimize: true,
567
+ autoIndex: null,
568
+ discriminatorKey: '__t',
569
+ shardKey: null,
570
+ read: null,
571
+ validateBeforeSave: true,
572
+ // the following are only applied at construction time
573
+ _id: true,
574
+ id: id,
575
+ typeKey: 'type'
576
+ }, utils.clone(options));
577
+
578
+ if (options.read) {
579
+ options.read = readPref(options.read);
580
+ }
581
+
582
+ if (options.versionKey && typeof options.versionKey !== 'string') {
583
+ throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`');
584
+ }
585
+
586
+ if (options.optimisticConcurrency && !options.versionKey) {
587
+ throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
588
+ }
589
+
590
+ return options;
591
+ };
592
+
593
+ /**
594
+ * Inherit a Schema by applying a discriminator on an existing Schema.
595
+ *
596
+ *
597
+ * #### Example:
598
+ *
599
+ * const eventSchema = new mongoose.Schema({ timestamp: Date }, { discriminatorKey: 'kind' });
600
+ *
601
+ * const clickedEventSchema = new mongoose.Schema({ element: String }, { discriminatorKey: 'kind' });
602
+ * const ClickedModel = eventSchema.discriminator('clicked', clickedEventSchema);
603
+ *
604
+ * const Event = mongoose.model('Event', eventSchema);
605
+ *
606
+ * Event.discriminators['clicked']; // Model { clicked }
607
+ *
608
+ * const doc = await Event.create({ kind: 'clicked', element: '#hero' });
609
+ * doc.element; // '#hero'
610
+ * doc instanceof ClickedModel; // true
611
+ *
612
+ * @param {String} name the name of the discriminator
613
+ * @param {Schema} schema the discriminated Schema
614
+ * @return {Schema} the Schema instance
615
+ * @api public
616
+ */
617
+ Schema.prototype.discriminator = function(name, schema) {
618
+ this._applyDiscriminators = Object.assign(this._applyDiscriminators || {}, { [name]: schema });
619
+
620
+ return this;
621
+ };
622
+
623
+ /**
624
+ * Adds key path / schema type pairs to this schema.
625
+ *
626
+ * #### Example:
627
+ *
628
+ * const ToySchema = new Schema();
629
+ * ToySchema.add({ name: 'string', color: 'string', price: 'number' });
630
+ *
631
+ * const TurboManSchema = new Schema();
632
+ * // You can also `add()` another schema and copy over all paths, virtuals,
633
+ * // getters, setters, indexes, methods, and statics.
634
+ * TurboManSchema.add(ToySchema).add({ year: Number });
635
+ *
636
+ * @param {Object|Schema} obj plain object with paths to add, or another schema
637
+ * @param {String} [prefix] path to prefix the newly added paths with
638
+ * @return {Schema} the Schema instance
639
+ * @api public
640
+ */
641
+
642
+ Schema.prototype.add = function add(obj, prefix) {
643
+ if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
644
+ merge(this, obj);
645
+
646
+ return this;
647
+ }
648
+
649
+ // Special case: setting top-level `_id` to false should convert to disabling
650
+ // the `_id` option. This behavior never worked before 5.4.11 but numerous
651
+ // codebases use it (see gh-7516, gh-7512).
652
+ if (obj._id === false && prefix == null) {
653
+ this.options._id = false;
654
+ }
655
+
656
+ prefix = prefix || '';
657
+ // avoid prototype pollution
658
+ if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
659
+ return this;
660
+ }
661
+
662
+ const keys = Object.keys(obj);
663
+ const typeKey = this.options.typeKey;
664
+ for (const key of keys) {
665
+ if (utils.specialProperties.has(key)) {
666
+ continue;
667
+ }
668
+
669
+ const fullPath = prefix + key;
670
+ const val = obj[key];
671
+
672
+ if (val == null) {
673
+ throw new TypeError('Invalid value for schema path `' + fullPath +
674
+ '`, got value "' + val + '"');
675
+ }
676
+ // Retain `_id: false` but don't set it as a path, re: gh-8274.
677
+ if (key === '_id' && val === false) {
678
+ continue;
679
+ }
680
+ if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === 'VirtualType') {
681
+ this.virtual(val);
682
+ continue;
683
+ }
684
+
685
+ if (Array.isArray(val) && val.length === 1 && val[0] == null) {
686
+ throw new TypeError('Invalid value for schema Array path `' + fullPath +
687
+ '`, got value "' + val[0] + '"');
688
+ }
689
+
690
+ if (!(isPOJO(val) || val instanceof SchemaTypeOptions)) {
691
+ // Special-case: Non-options definitely a path so leaf at this node
692
+ // Examples: Schema instances, SchemaType instances
693
+ if (prefix) {
694
+ this.nested[prefix.substring(0, prefix.length - 1)] = true;
695
+ }
696
+ this.path(prefix + key, val);
697
+ if (val[0] != null && !(val[0].instanceOfSchema) && utils.isPOJO(val[0].discriminators)) {
698
+ const schemaType = this.path(prefix + key);
699
+ for (const key in val[0].discriminators) {
700
+ schemaType.discriminator(key, val[0].discriminators[key]);
701
+ }
702
+ } else if (val[0] != null && val[0].instanceOfSchema && utils.isPOJO(val[0]._applyDiscriminators)) {
703
+ const applyDiscriminators = val[0]._applyDiscriminators || [];
704
+ const schemaType = this.path(prefix + key);
705
+ for (const disc in applyDiscriminators) {
706
+ schemaType.discriminator(disc, applyDiscriminators[disc]);
707
+ }
708
+ }
709
+ else if (val != null && val.instanceOfSchema && utils.isPOJO(val._applyDiscriminators)) {
710
+ const applyDiscriminators = val._applyDiscriminators || [];
711
+ const schemaType = this.path(prefix + key);
712
+ for (const disc in applyDiscriminators) {
713
+ schemaType.discriminator(disc, applyDiscriminators[disc]);
714
+ }
715
+ }
716
+ } else if (Object.keys(val).length < 1) {
717
+ // Special-case: {} always interpreted as Mixed path so leaf at this node
718
+ if (prefix) {
719
+ this.nested[prefix.substring(0, prefix.length - 1)] = true;
720
+ }
721
+ this.path(fullPath, val); // mixed type
722
+ } else if (!val[typeKey] || (typeKey === 'type' && isPOJO(val.type) && val.type.type)) {
723
+ // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse
724
+ // nested object `{ last: { name: String } }`. Avoid functions with `.type` re: #10807 because
725
+ // NestJS sometimes adds `Date.type`.
726
+ this.nested[fullPath] = true;
727
+ this.add(val, fullPath + '.');
728
+ } else {
729
+ // There IS a bona-fide type key that may also be a POJO
730
+ const _typeDef = val[typeKey];
731
+ if (isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) {
732
+ // If a POJO is the value of a type key, make it a subdocument
733
+ if (prefix) {
734
+ this.nested[prefix.substring(0, prefix.length - 1)] = true;
735
+ }
736
+ const _schema = new Schema(_typeDef);
737
+ const schemaWrappedPath = Object.assign({}, val, { type: _schema });
738
+ this.path(prefix + key, schemaWrappedPath);
739
+ } else {
740
+ // Either the type is non-POJO or we interpret it as Mixed anyway
741
+ if (prefix) {
742
+ this.nested[prefix.substring(0, prefix.length - 1)] = true;
743
+ }
744
+ this.path(prefix + key, val);
745
+ if (val != null && !(val.instanceOfSchema) && utils.isPOJO(val.discriminators)) {
746
+ const schemaType = this.path(prefix + key);
747
+ for (const key in val.discriminators) {
748
+ schemaType.discriminator(key, val.discriminators[key]);
749
+ }
750
+ }
751
+ }
752
+ }
753
+ }
754
+
755
+ const aliasObj = Object.fromEntries(
756
+ Object.entries(obj).map(([key]) => ([prefix + key, null]))
757
+ );
758
+ aliasFields(this, aliasObj);
759
+ return this;
760
+ };
761
+
762
+ /**
763
+ * Add an alias for `path`. This means getting or setting the `alias`
764
+ * is equivalent to getting or setting the `path`.
765
+ *
766
+ * #### Example:
767
+ *
768
+ * const toySchema = new Schema({ n: String });
769
+ *
770
+ * // Make 'name' an alias for 'n'
771
+ * toySchema.alias('n', 'name');
772
+ *
773
+ * const Toy = mongoose.model('Toy', toySchema);
774
+ * const turboMan = new Toy({ n: 'Turbo Man' });
775
+ *
776
+ * turboMan.name; // 'Turbo Man'
777
+ * turboMan.n; // 'Turbo Man'
778
+ *
779
+ * turboMan.name = 'Turbo Man Action Figure';
780
+ * turboMan.n; // 'Turbo Man Action Figure'
781
+ *
782
+ * await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' }
783
+ *
784
+ *
785
+ * @param {String} path real path to alias
786
+ * @param {String|String[]} alias the path(s) to use as an alias for `path`
787
+ * @return {Schema} the Schema instance
788
+ * @api public
789
+ */
790
+
791
+ Schema.prototype.alias = function alias(path, alias) {
792
+ aliasFields(this, { [path]: alias });
793
+ return this;
794
+ };
795
+
796
+ /**
797
+ * Remove an index by name or index specification.
798
+ *
799
+ * removeIndex only removes indexes from your schema object. Does **not** affect the indexes
800
+ * in MongoDB.
801
+ *
802
+ * #### Example:
803
+ *
804
+ * const ToySchema = new Schema({ name: String, color: String, price: Number });
805
+ *
806
+ * // Add a new index on { name, color }
807
+ * ToySchema.index({ name: 1, color: 1 });
808
+ *
809
+ * // Remove index on { name, color }
810
+ * // Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index
811
+ * ToySchema.removeIndex({ name: 1, color: 1 });
812
+ *
813
+ * // Add an index with a custom name
814
+ * ToySchema.index({ color: 1 }, { name: 'my custom index name' });
815
+ * // Remove index by name
816
+ * ToySchema.removeIndex('my custom index name');
817
+ *
818
+ * @param {Object|string} index name or index specification
819
+ * @return {Schema} the Schema instance
820
+ * @api public
821
+ */
822
+
823
+ Schema.prototype.removeIndex = function removeIndex(index) {
824
+ if (arguments.length > 1) {
825
+ throw new Error('removeIndex() takes only 1 argument');
826
+ }
827
+
828
+ if (typeof index !== 'object' && typeof index !== 'string') {
829
+ throw new Error('removeIndex() may only take either an object or a string as an argument');
830
+ }
831
+
832
+ if (typeof index === 'object') {
833
+ for (let i = this._indexes.length - 1; i >= 0; --i) {
834
+ if (util.isDeepStrictEqual(this._indexes[i][0], index)) {
835
+ this._indexes.splice(i, 1);
836
+ }
837
+ }
838
+ } else {
839
+ for (let i = this._indexes.length - 1; i >= 0; --i) {
840
+ if (this._indexes[i][1] != null && this._indexes[i][1].name === index) {
841
+ this._indexes.splice(i, 1);
842
+ }
843
+ }
844
+ }
845
+
846
+ return this;
847
+ };
848
+
849
+ /**
850
+ * Remove all indexes from this schema.
851
+ *
852
+ * clearIndexes only removes indexes from your schema object. Does **not** affect the indexes
853
+ * in MongoDB.
854
+ *
855
+ * #### Example:
856
+ *
857
+ * const ToySchema = new Schema({ name: String, color: String, price: Number });
858
+ * ToySchema.index({ name: 1 });
859
+ * ToySchema.index({ color: 1 });
860
+ *
861
+ * // Remove all indexes on this schema
862
+ * ToySchema.clearIndexes();
863
+ *
864
+ * ToySchema.indexes(); // []
865
+ *
866
+ * @return {Schema} the Schema instance
867
+ * @api public
868
+ */
869
+
870
+ Schema.prototype.clearIndexes = function clearIndexes() {
871
+ this._indexes.length = 0;
872
+
873
+ return this;
874
+ };
875
+
876
+ /**
877
+ * Reserved document keys.
878
+ *
879
+ * Keys in this object are names that are warned in schema declarations
880
+ * because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema
881
+ * using `new Schema()` with one of these property names, Mongoose will log a warning.
882
+ *
883
+ * - _posts
884
+ * - _pres
885
+ * - collection
886
+ * - emit
887
+ * - errors
888
+ * - get
889
+ * - init
890
+ * - isModified
891
+ * - isNew
892
+ * - listeners
893
+ * - modelName
894
+ * - on
895
+ * - once
896
+ * - populated
897
+ * - prototype
898
+ * - remove
899
+ * - removeListener
900
+ * - save
901
+ * - schema
902
+ * - toObject
903
+ * - validate
904
+ *
905
+ * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.
906
+ *
907
+ * const schema = new Schema(..);
908
+ * schema.methods.init = function () {} // potentially breaking
909
+ *
910
+ * @property reserved
911
+ * @memberOf Schema
912
+ * @static
913
+ */
914
+
915
+ Schema.reserved = Object.create(null);
916
+ Schema.prototype.reserved = Schema.reserved;
917
+
918
+ const reserved = Schema.reserved;
919
+ // Core object
920
+ reserved['prototype'] =
921
+ // EventEmitter
922
+ reserved.emit =
923
+ reserved.listeners =
924
+ reserved.removeListener =
925
+
926
+ // document properties and functions
927
+ reserved.collection =
928
+ reserved.errors =
929
+ reserved.get =
930
+ reserved.init =
931
+ reserved.isModified =
932
+ reserved.isNew =
933
+ reserved.populated =
934
+ reserved.remove =
935
+ reserved.save =
936
+ reserved.toObject =
937
+ reserved.validate = 1;
938
+ reserved.collection = 1;
939
+
940
+ /**
941
+ * Gets/sets schema paths.
942
+ *
943
+ * Sets a path (if arity 2)
944
+ * Gets a path (if arity 1)
945
+ *
946
+ * #### Example:
947
+ *
948
+ * schema.path('name') // returns a SchemaType
949
+ * schema.path('name', Number) // changes the schemaType of `name` to Number
950
+ *
951
+ * @param {String} path The name of the Path to get / set
952
+ * @param {Object} [obj] The Type to set the path to, if provided the path will be SET, otherwise the path will be GET
953
+ * @api public
954
+ */
955
+
956
+ Schema.prototype.path = function(path, obj) {
957
+ if (obj === undefined) {
958
+ if (this.paths[path] != null) {
959
+ return this.paths[path];
960
+ }
961
+ // Convert to '.$' to check subpaths re: gh-6405
962
+ const cleanPath = _pathToPositionalSyntax(path);
963
+ let schematype = _getPath(this, path, cleanPath);
964
+ if (schematype != null) {
965
+ return schematype;
966
+ }
967
+
968
+ // Look for maps
969
+ const mapPath = getMapPath(this, path);
970
+ if (mapPath != null) {
971
+ return mapPath;
972
+ }
973
+
974
+ // Look if a parent of this path is mixed
975
+ schematype = this.hasMixedParent(cleanPath);
976
+ if (schematype != null) {
977
+ return schematype;
978
+ }
979
+
980
+ // subpaths?
981
+ return hasNumericSubpathRegex.test(path)
982
+ ? getPositionalPath(this, path)
983
+ : undefined;
984
+ }
985
+
986
+ // some path names conflict with document methods
987
+ const firstPieceOfPath = path.split('.')[0];
988
+ if (reserved[firstPieceOfPath] && !this.options.supressReservedKeysWarning) {
989
+ const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. ` +
990
+ 'You are allowed to use it, but use at your own risk. ' +
991
+ 'To disable this warning pass `supressReservedKeysWarning` as a schema option.';
992
+
993
+ utils.warn(errorMessage);
994
+ }
995
+
996
+ if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
997
+ validateRef(obj.ref, path);
998
+ }
999
+
1000
+ // update the tree
1001
+ const subpaths = path.split(/\./);
1002
+ const last = subpaths.pop();
1003
+ let branch = this.tree;
1004
+ let fullPath = '';
1005
+
1006
+ for (const sub of subpaths) {
1007
+ if (utils.specialProperties.has(sub)) {
1008
+ throw new Error('Cannot set special property `' + sub + '` on a schema');
1009
+ }
1010
+ fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub;
1011
+ if (!branch[sub]) {
1012
+ this.nested[fullPath] = true;
1013
+ branch[sub] = {};
1014
+ }
1015
+ if (typeof branch[sub] !== 'object') {
1016
+ const msg = 'Cannot set nested path `' + path + '`. '
1017
+ + 'Parent path `'
1018
+ + fullPath
1019
+ + '` already set to type ' + branch[sub].name
1020
+ + '.';
1021
+ throw new Error(msg);
1022
+ }
1023
+ branch = branch[sub];
1024
+ }
1025
+
1026
+ branch[last] = utils.clone(obj);
1027
+
1028
+ this.paths[path] = this.interpretAsType(path, obj, this.options);
1029
+ const schemaType = this.paths[path];
1030
+
1031
+ if (schemaType.$isSchemaMap) {
1032
+ // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
1033
+ // The '$' is to imply this path should never be stored in MongoDB so we
1034
+ // can easily build a regexp out of this path, and '*' to imply "any key."
1035
+ const mapPath = path + '.$*';
1036
+
1037
+ this.paths[mapPath] = schemaType.$__schemaType;
1038
+ this.mapPaths.push(this.paths[mapPath]);
1039
+ }
1040
+
1041
+ if (schemaType.$isSingleNested) {
1042
+ for (const key of Object.keys(schemaType.schema.paths)) {
1043
+ this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
1044
+ }
1045
+ for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
1046
+ this.singleNestedPaths[path + '.' + key] =
1047
+ schemaType.schema.singleNestedPaths[key];
1048
+ }
1049
+ for (const key of Object.keys(schemaType.schema.subpaths)) {
1050
+ this.singleNestedPaths[path + '.' + key] =
1051
+ schemaType.schema.subpaths[key];
1052
+ }
1053
+ for (const key of Object.keys(schemaType.schema.nested)) {
1054
+ this.singleNestedPaths[path + '.' + key] = 'nested';
1055
+ }
1056
+
1057
+ Object.defineProperty(schemaType.schema, 'base', {
1058
+ configurable: true,
1059
+ enumerable: false,
1060
+ writable: false,
1061
+ value: this.base
1062
+ });
1063
+
1064
+ schemaType.caster.base = this.base;
1065
+ this.childSchemas.push({
1066
+ schema: schemaType.schema,
1067
+ model: schemaType.caster
1068
+ });
1069
+ } else if (schemaType.$isMongooseDocumentArray) {
1070
+ Object.defineProperty(schemaType.schema, 'base', {
1071
+ configurable: true,
1072
+ enumerable: false,
1073
+ writable: false,
1074
+ value: this.base
1075
+ });
1076
+
1077
+ schemaType.casterConstructor.base = this.base;
1078
+ this.childSchemas.push({
1079
+ schema: schemaType.schema,
1080
+ model: schemaType.casterConstructor
1081
+ });
1082
+ }
1083
+
1084
+ if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) {
1085
+ let arrayPath = path;
1086
+ let _schemaType = schemaType;
1087
+
1088
+ const toAdd = [];
1089
+ while (_schemaType.$isMongooseArray) {
1090
+ arrayPath = arrayPath + '.$';
1091
+
1092
+ // Skip arrays of document arrays
1093
+ if (_schemaType.$isMongooseDocumentArray) {
1094
+ _schemaType.$embeddedSchemaType._arrayPath = arrayPath;
1095
+ _schemaType.$embeddedSchemaType._arrayParentPath = path;
1096
+ _schemaType = _schemaType.$embeddedSchemaType.clone();
1097
+ } else {
1098
+ _schemaType.caster._arrayPath = arrayPath;
1099
+ _schemaType.caster._arrayParentPath = path;
1100
+ _schemaType = _schemaType.caster.clone();
1101
+ }
1102
+
1103
+ _schemaType.path = arrayPath;
1104
+ toAdd.push(_schemaType);
1105
+ }
1106
+
1107
+ for (const _schemaType of toAdd) {
1108
+ this.subpaths[_schemaType.path] = _schemaType;
1109
+ }
1110
+ }
1111
+
1112
+ if (schemaType.$isMongooseDocumentArray) {
1113
+ for (const key of Object.keys(schemaType.schema.paths)) {
1114
+ const _schemaType = schemaType.schema.paths[key];
1115
+ this.subpaths[path + '.' + key] = _schemaType;
1116
+ if (typeof _schemaType === 'object' && _schemaType != null) {
1117
+ _schemaType.$isUnderneathDocArray = true;
1118
+ }
1119
+ }
1120
+ for (const key of Object.keys(schemaType.schema.subpaths)) {
1121
+ const _schemaType = schemaType.schema.subpaths[key];
1122
+ this.subpaths[path + '.' + key] = _schemaType;
1123
+ if (typeof _schemaType === 'object' && _schemaType != null) {
1124
+ _schemaType.$isUnderneathDocArray = true;
1125
+ }
1126
+ }
1127
+ for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
1128
+ const _schemaType = schemaType.schema.singleNestedPaths[key];
1129
+ this.subpaths[path + '.' + key] = _schemaType;
1130
+ if (typeof _schemaType === 'object' && _schemaType != null) {
1131
+ _schemaType.$isUnderneathDocArray = true;
1132
+ }
1133
+ }
1134
+ }
1135
+
1136
+ return this;
1137
+ };
1138
+
1139
+ /*!
1140
+ * ignore
1141
+ */
1142
+
1143
+ function gatherChildSchemas(schema) {
1144
+ const childSchemas = [];
1145
+
1146
+ for (const path of Object.keys(schema.paths)) {
1147
+ const schematype = schema.paths[path];
1148
+ if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
1149
+ childSchemas.push({ schema: schematype.schema, model: schematype.caster });
1150
+ }
1151
+ }
1152
+
1153
+ return childSchemas;
1154
+ }
1155
+
1156
+ /*!
1157
+ * ignore
1158
+ */
1159
+
1160
+ function _getPath(schema, path, cleanPath) {
1161
+ if (schema.paths.hasOwnProperty(path)) {
1162
+ return schema.paths[path];
1163
+ }
1164
+ if (schema.subpaths.hasOwnProperty(cleanPath)) {
1165
+ return schema.subpaths[cleanPath];
1166
+ }
1167
+ if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
1168
+ return schema.singleNestedPaths[cleanPath];
1169
+ }
1170
+
1171
+ return null;
1172
+ }
1173
+
1174
+ /*!
1175
+ * ignore
1176
+ */
1177
+
1178
+ function _pathToPositionalSyntax(path) {
1179
+ if (!/\.\d+/.test(path)) {
1180
+ return path;
1181
+ }
1182
+ return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$');
1183
+ }
1184
+
1185
+ /*!
1186
+ * ignore
1187
+ */
1188
+
1189
+ function getMapPath(schema, path) {
1190
+ if (schema.mapPaths.length === 0) {
1191
+ return null;
1192
+ }
1193
+ for (const val of schema.mapPaths) {
1194
+ const _path = val.path;
1195
+ const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
1196
+ if (re.test(path)) {
1197
+ return schema.paths[_path];
1198
+ }
1199
+ }
1200
+
1201
+ return null;
1202
+ }
1203
+
1204
+ /**
1205
+ * The Mongoose instance this schema is associated with
1206
+ *
1207
+ * @property base
1208
+ * @api private
1209
+ */
1210
+
1211
+ Object.defineProperty(Schema.prototype, 'base', {
1212
+ configurable: true,
1213
+ enumerable: false,
1214
+ writable: true,
1215
+ value: null
1216
+ });
1217
+
1218
+ /**
1219
+ * Converts type arguments into Mongoose Types.
1220
+ *
1221
+ * @param {String} path
1222
+ * @param {Object} obj constructor
1223
+ * @param {Object} options
1224
+ * @api private
1225
+ */
1226
+
1227
+ Schema.prototype.interpretAsType = function(path, obj, options) {
1228
+ if (obj instanceof SchemaType) {
1229
+ if (obj.path === path) {
1230
+ return obj;
1231
+ }
1232
+ const clone = obj.clone();
1233
+ clone.path = path;
1234
+ return clone;
1235
+ }
1236
+
1237
+ // If this schema has an associated Mongoose object, use the Mongoose object's
1238
+ // copy of SchemaTypes re: gh-7158 gh-6933
1239
+ const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
1240
+ const Types = this.base != null ? this.base.Types : require('./types');
1241
+
1242
+ if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) {
1243
+ const constructorName = utils.getFunctionName(obj.constructor);
1244
+ if (constructorName !== 'Object') {
1245
+ const oldObj = obj;
1246
+ obj = {};
1247
+ obj[options.typeKey] = oldObj;
1248
+ }
1249
+ }
1250
+
1251
+ // Get the type making sure to allow keys named "type"
1252
+ // and default to mixed if not specified.
1253
+ // { type: { type: String, default: 'freshcut' } }
1254
+ let type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== 'type' || !obj.type.type)
1255
+ ? obj[options.typeKey]
1256
+ : {};
1257
+ let name;
1258
+
1259
+ if (utils.isPOJO(type) || type === 'mixed') {
1260
+ return new MongooseTypes.Mixed(path, obj);
1261
+ }
1262
+
1263
+ if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) {
1264
+ // if it was specified through { type } look for `cast`
1265
+ let cast = (type === Array || type === 'array')
1266
+ ? obj.cast || obj.of
1267
+ : type[0];
1268
+
1269
+ // new Schema({ path: [new Schema({ ... })] })
1270
+ if (cast && cast.instanceOfSchema) {
1271
+ if (!(cast instanceof Schema)) {
1272
+ throw new TypeError('Schema for array path `' + path +
1273
+ '` is from a different copy of the Mongoose module. ' +
1274
+ 'Please make sure you\'re using the same version ' +
1275
+ 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1276
+ 'getting this error, please add `new Schema()` around the path: ' +
1277
+ `${path}: new Schema(...)`);
1278
+ }
1279
+ return new MongooseTypes.DocumentArray(path, cast, obj);
1280
+ }
1281
+ if (cast &&
1282
+ cast[options.typeKey] &&
1283
+ cast[options.typeKey].instanceOfSchema) {
1284
+ if (!(cast[options.typeKey] instanceof Schema)) {
1285
+ throw new TypeError('Schema for array path `' + path +
1286
+ '` is from a different copy of the Mongoose module. ' +
1287
+ 'Please make sure you\'re using the same version ' +
1288
+ 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1289
+ 'getting this error, please add `new Schema()` around the path: ' +
1290
+ `${path}: new Schema(...)`);
1291
+ }
1292
+ return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
1293
+ }
1294
+
1295
+ if (Array.isArray(cast)) {
1296
+ return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
1297
+ }
1298
+
1299
+ // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })`
1300
+ const castFromTypeKey = (cast != null && cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)) ?
1301
+ cast[options.typeKey] :
1302
+ cast;
1303
+ if (typeof cast === 'string') {
1304
+ cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
1305
+ } else if (utils.isPOJO(castFromTypeKey)) {
1306
+ if (Object.keys(castFromTypeKey).length) {
1307
+ // The `minimize` and `typeKey` options propagate to child schemas
1308
+ // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
1309
+ // See gh-3560
1310
+ const childSchemaOptions = { minimize: options.minimize };
1311
+ if (options.typeKey) {
1312
+ childSchemaOptions.typeKey = options.typeKey;
1313
+ }
1314
+ // propagate 'strict' option to child schema
1315
+ if (options.hasOwnProperty('strict')) {
1316
+ childSchemaOptions.strict = options.strict;
1317
+ }
1318
+ if (options.hasOwnProperty('strictQuery')) {
1319
+ childSchemaOptions.strictQuery = options.strictQuery;
1320
+ }
1321
+
1322
+ if (this._userProvidedOptions.hasOwnProperty('_id')) {
1323
+ childSchemaOptions._id = this._userProvidedOptions._id;
1324
+ } else if (Schema.Types.DocumentArray.defaultOptions._id != null) {
1325
+ childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id;
1326
+ }
1327
+ const childSchema = new Schema(castFromTypeKey, childSchemaOptions);
1328
+ childSchema.$implicitlyCreated = true;
1329
+ return new MongooseTypes.DocumentArray(path, childSchema, obj);
1330
+ } else {
1331
+ // Special case: empty object becomes mixed
1332
+ return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
1333
+ }
1334
+ }
1335
+
1336
+ if (cast) {
1337
+ type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
1338
+ ? cast[options.typeKey]
1339
+ : cast;
1340
+
1341
+ if (Array.isArray(type)) {
1342
+ return new MongooseTypes.Array(path, this.interpretAsType(path, type, options), obj);
1343
+ }
1344
+
1345
+ name = typeof type === 'string'
1346
+ ? type
1347
+ : type.schemaName || utils.getFunctionName(type);
1348
+
1349
+ // For Jest 26+, see #10296
1350
+ if (name === 'ClockDate') {
1351
+ name = 'Date';
1352
+ }
1353
+
1354
+ if (name === void 0) {
1355
+ throw new TypeError('Invalid schema configuration: ' +
1356
+ `Could not determine the embedded type for array \`${path}\`. ` +
1357
+ 'See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
1358
+ }
1359
+ if (!MongooseTypes.hasOwnProperty(name)) {
1360
+ throw new TypeError('Invalid schema configuration: ' +
1361
+ `\`${name}\` is not a valid type within the array \`${path}\`.` +
1362
+ 'See https://bit.ly/mongoose-schematypes for a list of valid schema types.');
1363
+ }
1364
+ }
1365
+
1366
+ return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
1367
+ }
1368
+
1369
+ if (type && type.instanceOfSchema) {
1370
+
1371
+ return new MongooseTypes.Subdocument(type, path, obj);
1372
+ }
1373
+
1374
+ if (Buffer.isBuffer(type)) {
1375
+ name = 'Buffer';
1376
+ } else if (typeof type === 'function' || typeof type === 'object') {
1377
+ name = type.schemaName || utils.getFunctionName(type);
1378
+ } else if (type === Types.ObjectId) {
1379
+ name = 'ObjectId';
1380
+ } else if (type === Types.Decimal128) {
1381
+ name = 'Decimal128';
1382
+ } else {
1383
+ name = type == null ? '' + type : type.toString();
1384
+ }
1385
+
1386
+ if (name) {
1387
+ name = name.charAt(0).toUpperCase() + name.substring(1);
1388
+ }
1389
+ // Special case re: gh-7049 because the bson `ObjectID` class' capitalization
1390
+ // doesn't line up with Mongoose's.
1391
+ if (name === 'ObjectID') {
1392
+ name = 'ObjectId';
1393
+ }
1394
+ // For Jest 26+, see #10296
1395
+ if (name === 'ClockDate') {
1396
+ name = 'Date';
1397
+ }
1398
+
1399
+ if (name === void 0) {
1400
+ throw new TypeError(`Invalid schema configuration: \`${path}\` schematype definition is ` +
1401
+ 'invalid. See ' +
1402
+ 'https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
1403
+ }
1404
+ if (MongooseTypes[name] == null) {
1405
+ throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
1406
+ `a valid type at path \`${path}\`. See ` +
1407
+ 'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
1408
+ }
1409
+
1410
+ const schemaType = new MongooseTypes[name](path, obj);
1411
+
1412
+ if (schemaType.$isSchemaMap) {
1413
+ createMapNestedSchemaType(this, schemaType, path, obj, options);
1414
+ }
1415
+
1416
+ return schemaType;
1417
+ };
1418
+
1419
+ /*!
1420
+ * ignore
1421
+ */
1422
+
1423
+ function createMapNestedSchemaType(schema, schemaType, path, obj, options) {
1424
+ const mapPath = path + '.$*';
1425
+ let _mapType = { type: {} };
1426
+ if (utils.hasUserDefinedProperty(obj, 'of')) {
1427
+ const isInlineSchema = utils.isPOJO(obj.of) &&
1428
+ Object.keys(obj.of).length > 0 &&
1429
+ !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey);
1430
+ if (isInlineSchema) {
1431
+ _mapType = { [schema.options.typeKey]: new Schema(obj.of) };
1432
+ } else if (utils.isPOJO(obj.of)) {
1433
+ _mapType = Object.assign({}, obj.of);
1434
+ } else {
1435
+ _mapType = { [schema.options.typeKey]: obj.of };
1436
+ }
1437
+
1438
+ if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) {
1439
+ const subdocumentSchema = _mapType[schema.options.typeKey];
1440
+ subdocumentSchema.eachPath((subpath, type) => {
1441
+ if (type.options.select === true || type.options.select === false) {
1442
+ throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + '.' + subpath + '"');
1443
+ }
1444
+ });
1445
+ }
1446
+
1447
+ if (utils.hasUserDefinedProperty(obj, 'ref')) {
1448
+ _mapType.ref = obj.ref;
1449
+ }
1450
+ }
1451
+ schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options);
1452
+ }
1453
+
1454
+ /**
1455
+ * Iterates the schemas paths similar to Array#forEach.
1456
+ *
1457
+ * The callback is passed the pathname and the schemaType instance.
1458
+ *
1459
+ * #### Example:
1460
+ *
1461
+ * const userSchema = new Schema({ name: String, registeredAt: Date });
1462
+ * userSchema.eachPath((pathname, schematype) => {
1463
+ * // Prints twice:
1464
+ * // name SchemaString { ... }
1465
+ * // registeredAt SchemaDate { ... }
1466
+ * console.log(pathname, schematype);
1467
+ * });
1468
+ *
1469
+ * @param {Function} fn callback function
1470
+ * @return {Schema} this
1471
+ * @api public
1472
+ */
1473
+
1474
+ Schema.prototype.eachPath = function(fn) {
1475
+ const keys = Object.keys(this.paths);
1476
+ const len = keys.length;
1477
+
1478
+ for (let i = 0; i < len; ++i) {
1479
+ fn(keys[i], this.paths[keys[i]]);
1480
+ }
1481
+
1482
+ return this;
1483
+ };
1484
+
1485
+ /**
1486
+ * Returns an Array of path strings that are required by this schema.
1487
+ *
1488
+ * #### Example:
1489
+ *
1490
+ * const s = new Schema({
1491
+ * name: { type: String, required: true },
1492
+ * age: { type: String, required: true },
1493
+ * notes: String
1494
+ * });
1495
+ * s.requiredPaths(); // [ 'age', 'name' ]
1496
+ *
1497
+ * @api public
1498
+ * @param {Boolean} invalidate Refresh the cache
1499
+ * @return {Array}
1500
+ */
1501
+
1502
+ Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
1503
+ if (this._requiredpaths && !invalidate) {
1504
+ return this._requiredpaths;
1505
+ }
1506
+
1507
+ const paths = Object.keys(this.paths);
1508
+ let i = paths.length;
1509
+ const ret = [];
1510
+
1511
+ while (i--) {
1512
+ const path = paths[i];
1513
+ if (this.paths[path].isRequired) {
1514
+ ret.push(path);
1515
+ }
1516
+ }
1517
+ this._requiredpaths = ret;
1518
+ return this._requiredpaths;
1519
+ };
1520
+
1521
+ /**
1522
+ * Returns indexes from fields and schema-level indexes (cached).
1523
+ *
1524
+ * @api private
1525
+ * @return {Array}
1526
+ */
1527
+
1528
+ Schema.prototype.indexedPaths = function indexedPaths() {
1529
+ if (this._indexedpaths) {
1530
+ return this._indexedpaths;
1531
+ }
1532
+ this._indexedpaths = this.indexes();
1533
+ return this._indexedpaths;
1534
+ };
1535
+
1536
+ /**
1537
+ * Returns the pathType of `path` for this schema.
1538
+ *
1539
+ * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
1540
+ *
1541
+ * #### Example:
1542
+ *
1543
+ * const s = new Schema({ name: String, nested: { foo: String } });
1544
+ * s.virtual('foo').get(() => 42);
1545
+ * s.pathType('name'); // "real"
1546
+ * s.pathType('nested'); // "nested"
1547
+ * s.pathType('foo'); // "virtual"
1548
+ * s.pathType('fail'); // "adhocOrUndefined"
1549
+ *
1550
+ * @param {String} path
1551
+ * @return {String}
1552
+ * @api public
1553
+ */
1554
+
1555
+ Schema.prototype.pathType = function(path) {
1556
+ if (this.paths.hasOwnProperty(path)) {
1557
+ return 'real';
1558
+ }
1559
+ if (this.virtuals.hasOwnProperty(path)) {
1560
+ return 'virtual';
1561
+ }
1562
+ if (this.nested.hasOwnProperty(path)) {
1563
+ return 'nested';
1564
+ }
1565
+
1566
+ // Convert to '.$' to check subpaths re: gh-6405
1567
+ const cleanPath = _pathToPositionalSyntax(path);
1568
+
1569
+ if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
1570
+ return 'real';
1571
+ }
1572
+
1573
+ const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path);
1574
+ if (singleNestedPath) {
1575
+ return singleNestedPath === 'nested' ? 'nested' : 'real';
1576
+ }
1577
+
1578
+ // Look for maps
1579
+ const mapPath = getMapPath(this, path);
1580
+ if (mapPath != null) {
1581
+ return 'real';
1582
+ }
1583
+
1584
+ if (/\.\d+\.|\.\d+$/.test(path)) {
1585
+ return getPositionalPathType(this, path);
1586
+ }
1587
+ return 'adhocOrUndefined';
1588
+ };
1589
+
1590
+ /**
1591
+ * Returns true iff this path is a child of a mixed schema.
1592
+ *
1593
+ * @param {String} path
1594
+ * @return {Boolean}
1595
+ * @api private
1596
+ */
1597
+
1598
+ Schema.prototype.hasMixedParent = function(path) {
1599
+ const subpaths = path.split(/\./g);
1600
+ path = '';
1601
+ for (let i = 0; i < subpaths.length; ++i) {
1602
+ path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
1603
+ if (this.paths.hasOwnProperty(path) &&
1604
+ this.paths[path] instanceof MongooseTypes.Mixed) {
1605
+ return this.paths[path];
1606
+ }
1607
+ }
1608
+
1609
+ return null;
1610
+ };
1611
+
1612
+ /**
1613
+ * Setup updatedAt and createdAt timestamps to documents if enabled
1614
+ *
1615
+ * @param {Boolean|Object} timestamps timestamps options
1616
+ * @api private
1617
+ */
1618
+ Schema.prototype.setupTimestamp = function(timestamps) {
1619
+ return setupTimestamps(this, timestamps);
1620
+ };
1621
+
1622
+ /**
1623
+ * ignore. Deprecated re: #6405
1624
+ * @param {Any} self
1625
+ * @param {String} path
1626
+ * @api private
1627
+ */
1628
+
1629
+ function getPositionalPathType(self, path) {
1630
+ const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
1631
+ if (subpaths.length < 2) {
1632
+ return self.paths.hasOwnProperty(subpaths[0]) ?
1633
+ self.paths[subpaths[0]] :
1634
+ 'adhocOrUndefined';
1635
+ }
1636
+
1637
+ let val = self.path(subpaths[0]);
1638
+ let isNested = false;
1639
+ if (!val) {
1640
+ return 'adhocOrUndefined';
1641
+ }
1642
+
1643
+ const last = subpaths.length - 1;
1644
+
1645
+ for (let i = 1; i < subpaths.length; ++i) {
1646
+ isNested = false;
1647
+ const subpath = subpaths[i];
1648
+
1649
+ if (i === last && val && !/\D/.test(subpath)) {
1650
+ if (val.$isMongooseDocumentArray) {
1651
+ val = val.$embeddedSchemaType;
1652
+ } else if (val instanceof MongooseTypes.Array) {
1653
+ // StringSchema, NumberSchema, etc
1654
+ val = val.caster;
1655
+ } else {
1656
+ val = undefined;
1657
+ }
1658
+ break;
1659
+ }
1660
+
1661
+ // ignore if its just a position segment: path.0.subpath
1662
+ if (!/\D/.test(subpath)) {
1663
+ // Nested array
1664
+ if (val instanceof MongooseTypes.Array && i !== last) {
1665
+ val = val.caster;
1666
+ }
1667
+ continue;
1668
+ }
1669
+
1670
+ if (!(val && val.schema)) {
1671
+ val = undefined;
1672
+ break;
1673
+ }
1674
+
1675
+ const type = val.schema.pathType(subpath);
1676
+ isNested = (type === 'nested');
1677
+ val = val.schema.path(subpath);
1678
+ }
1679
+
1680
+ self.subpaths[path] = val;
1681
+ if (val) {
1682
+ return 'real';
1683
+ }
1684
+ if (isNested) {
1685
+ return 'nested';
1686
+ }
1687
+ return 'adhocOrUndefined';
1688
+ }
1689
+
1690
+
1691
+ /*!
1692
+ * ignore
1693
+ */
1694
+
1695
+ function getPositionalPath(self, path) {
1696
+ getPositionalPathType(self, path);
1697
+ return self.subpaths[path];
1698
+ }
1699
+
1700
+ /**
1701
+ * Adds a method call to the queue.
1702
+ *
1703
+ * #### Example:
1704
+ *
1705
+ * schema.methods.print = function() { console.log(this); };
1706
+ * schema.queue('print', []); // Print the doc every one is instantiated
1707
+ *
1708
+ * const Model = mongoose.model('Test', schema);
1709
+ * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
1710
+ *
1711
+ * @param {String} name name of the document method to call later
1712
+ * @param {Array} args arguments to pass to the method
1713
+ * @api public
1714
+ */
1715
+
1716
+ Schema.prototype.queue = function(name, args) {
1717
+ this.callQueue.push([name, args]);
1718
+ return this;
1719
+ };
1720
+
1721
+ /**
1722
+ * Defines a pre hook for the model.
1723
+ *
1724
+ * #### Example:
1725
+ *
1726
+ * const toySchema = new Schema({ name: String, created: Date });
1727
+ *
1728
+ * toySchema.pre('save', function(next) {
1729
+ * if (!this.created) this.created = new Date;
1730
+ * next();
1731
+ * });
1732
+ *
1733
+ * toySchema.pre('validate', function(next) {
1734
+ * if (this.name !== 'Woody') this.name = 'Woody';
1735
+ * next();
1736
+ * });
1737
+ *
1738
+ * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
1739
+ * toySchema.pre(/^find/, function(next) {
1740
+ * console.log(this.getFilter());
1741
+ * });
1742
+ *
1743
+ * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
1744
+ * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
1745
+ * console.log(this.getFilter());
1746
+ * });
1747
+ *
1748
+ * toySchema.pre('deleteOne', function() {
1749
+ * // Runs when you call `Toy.deleteOne()`
1750
+ * });
1751
+ *
1752
+ * toySchema.pre('deleteOne', { document: true }, function() {
1753
+ * // Runs when you call `doc.deleteOne()`
1754
+ * });
1755
+ *
1756
+ * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1757
+ * @param {Object} [options]
1758
+ * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`.
1759
+ * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1760
+ * @param {Function} callback
1761
+ * @api public
1762
+ */
1763
+
1764
+ Schema.prototype.pre = function(name) {
1765
+ if (name instanceof RegExp) {
1766
+ const remainingArgs = Array.prototype.slice.call(arguments, 1);
1767
+ for (const fn of hookNames) {
1768
+ if (name.test(fn)) {
1769
+ this.pre.apply(this, [fn].concat(remainingArgs));
1770
+ }
1771
+ }
1772
+ return this;
1773
+ }
1774
+ if (Array.isArray(name)) {
1775
+ const remainingArgs = Array.prototype.slice.call(arguments, 1);
1776
+ for (const el of name) {
1777
+ this.pre.apply(this, [el].concat(remainingArgs));
1778
+ }
1779
+ return this;
1780
+ }
1781
+ this.s.hooks.pre.apply(this.s.hooks, arguments);
1782
+ return this;
1783
+ };
1784
+
1785
+ /**
1786
+ * Defines a post hook for the document
1787
+ *
1788
+ * const schema = new Schema(..);
1789
+ * schema.post('save', function (doc) {
1790
+ * console.log('this fired after a document was saved');
1791
+ * });
1792
+ *
1793
+ * schema.post('find', function(docs) {
1794
+ * console.log('this fired after you ran a find query');
1795
+ * });
1796
+ *
1797
+ * schema.post(/Many$/, function(res) {
1798
+ * console.log('this fired after you ran `updateMany()` or `deleteMany()`');
1799
+ * });
1800
+ *
1801
+ * const Model = mongoose.model('Model', schema);
1802
+ *
1803
+ * const m = new Model(..);
1804
+ * m.save(function(err) {
1805
+ * console.log('this fires after the `post` hook');
1806
+ * });
1807
+ *
1808
+ * m.find(function(err, docs) {
1809
+ * console.log('this fires after the post find hook');
1810
+ * });
1811
+ *
1812
+ * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1813
+ * @param {Object} [options]
1814
+ * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
1815
+ * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1816
+ * @param {Function} fn callback
1817
+ * @see middleware https://mongoosejs.com/docs/middleware.html
1818
+ * @see kareem https://npmjs.org/package/kareem
1819
+ * @api public
1820
+ */
1821
+
1822
+ Schema.prototype.post = function(name) {
1823
+ if (name instanceof RegExp) {
1824
+ const remainingArgs = Array.prototype.slice.call(arguments, 1);
1825
+ for (const fn of hookNames) {
1826
+ if (name.test(fn)) {
1827
+ this.post.apply(this, [fn].concat(remainingArgs));
1828
+ }
1829
+ }
1830
+ return this;
1831
+ }
1832
+ if (Array.isArray(name)) {
1833
+ const remainingArgs = Array.prototype.slice.call(arguments, 1);
1834
+ for (const el of name) {
1835
+ this.post.apply(this, [el].concat(remainingArgs));
1836
+ }
1837
+ return this;
1838
+ }
1839
+ this.s.hooks.post.apply(this.s.hooks, arguments);
1840
+ return this;
1841
+ };
1842
+
1843
+ /**
1844
+ * Registers a plugin for this schema.
1845
+ *
1846
+ * #### Example:
1847
+ *
1848
+ * const s = new Schema({ name: String });
1849
+ * s.plugin(schema => console.log(schema.path('name').path));
1850
+ * mongoose.model('Test', s); // Prints 'name'
1851
+ *
1852
+ * Or with Options:
1853
+ *
1854
+ * const s = new Schema({ name: String });
1855
+ * s.plugin((schema, opts) => console.log(opts.text, schema.path('name').path), { text: "Schema Path Name:" });
1856
+ * mongoose.model('Test', s); // Prints 'Schema Path Name: name'
1857
+ *
1858
+ * @param {Function} plugin The Plugin's callback
1859
+ * @param {Object} [opts] Options to pass to the plugin
1860
+ * @param {Boolean} [opts.deduplicate=false] If true, ignore duplicate plugins (same `fn` argument using `===`)
1861
+ * @see plugins /docs/plugins.html
1862
+ * @api public
1863
+ */
1864
+
1865
+ Schema.prototype.plugin = function(fn, opts) {
1866
+ if (typeof fn !== 'function') {
1867
+ throw new Error('First param to `schema.plugin()` must be a function, ' +
1868
+ 'got "' + (typeof fn) + '"');
1869
+ }
1870
+
1871
+ if (opts && opts.deduplicate) {
1872
+ for (const plugin of this.plugins) {
1873
+ if (plugin.fn === fn) {
1874
+ return this;
1875
+ }
1876
+ }
1877
+ }
1878
+ this.plugins.push({ fn: fn, opts: opts });
1879
+
1880
+ fn(this, opts);
1881
+ return this;
1882
+ };
1883
+
1884
+ /**
1885
+ * Adds an instance method to documents constructed from Models compiled from this schema.
1886
+ *
1887
+ * #### Example:
1888
+ *
1889
+ * const schema = kittySchema = new Schema(..);
1890
+ *
1891
+ * schema.method('meow', function () {
1892
+ * console.log('meeeeeoooooooooooow');
1893
+ * })
1894
+ *
1895
+ * const Kitty = mongoose.model('Kitty', schema);
1896
+ *
1897
+ * const fizz = new Kitty;
1898
+ * fizz.meow(); // meeeeeooooooooooooow
1899
+ *
1900
+ * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
1901
+ *
1902
+ * schema.method({
1903
+ * purr: function () {}
1904
+ * , scratch: function () {}
1905
+ * });
1906
+ *
1907
+ * // later
1908
+ * const fizz = new Kitty;
1909
+ * fizz.purr();
1910
+ * fizz.scratch();
1911
+ *
1912
+ * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods)
1913
+ *
1914
+ * @param {String|Object} name The Method Name for a single function, or a Object of "string-function" pairs.
1915
+ * @param {Function} [fn] The Function in a single-function definition.
1916
+ * @api public
1917
+ */
1918
+
1919
+ Schema.prototype.method = function(name, fn, options) {
1920
+ if (typeof name !== 'string') {
1921
+ for (const i in name) {
1922
+ this.methods[i] = name[i];
1923
+ this.methodOptions[i] = utils.clone(options);
1924
+ }
1925
+ } else {
1926
+ this.methods[name] = fn;
1927
+ this.methodOptions[name] = utils.clone(options);
1928
+ }
1929
+ return this;
1930
+ };
1931
+
1932
+ /**
1933
+ * Adds static "class" methods to Models compiled from this schema.
1934
+ *
1935
+ * #### Example:
1936
+ *
1937
+ * const schema = new Schema(..);
1938
+ * // Equivalent to `schema.statics.findByName = function(name) {}`;
1939
+ * schema.static('findByName', function(name) {
1940
+ * return this.find({ name: name });
1941
+ * });
1942
+ *
1943
+ * const Drink = mongoose.model('Drink', schema);
1944
+ * await Drink.findByName('LaCroix');
1945
+ *
1946
+ * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
1947
+ *
1948
+ * schema.static({
1949
+ * findByName: function () {..}
1950
+ * , findByCost: function () {..}
1951
+ * });
1952
+ *
1953
+ * const Drink = mongoose.model('Drink', schema);
1954
+ * await Drink.findByName('LaCroix');
1955
+ * await Drink.findByCost(3);
1956
+ *
1957
+ * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
1958
+ *
1959
+ * @param {String|Object} name The Method Name for a single function, or a Object of "string-function" pairs.
1960
+ * @param {Function} [fn] The Function in a single-function definition.
1961
+ * @api public
1962
+ * @see Statics /docs/guide.html#statics
1963
+ */
1964
+
1965
+ Schema.prototype.static = function(name, fn) {
1966
+ if (typeof name !== 'string') {
1967
+ for (const i in name) {
1968
+ this.statics[i] = name[i];
1969
+ }
1970
+ } else {
1971
+ this.statics[name] = fn;
1972
+ }
1973
+ return this;
1974
+ };
1975
+
1976
+ /**
1977
+ * Defines an index (most likely compound) for this schema.
1978
+ *
1979
+ * #### Example:
1980
+ *
1981
+ * schema.index({ first: 1, last: -1 })
1982
+ *
1983
+ * @param {Object} fields The Fields to index, with the order, available values: `1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'`
1984
+ * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#createIndex)
1985
+ * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
1986
+ * @param {String} [options.language_override=null] Tells mongodb to use the specified field instead of `language` for parsing text indexes.
1987
+ * @api public
1988
+ */
1989
+
1990
+ Schema.prototype.index = function(fields, options) {
1991
+ fields || (fields = {});
1992
+ options || (options = {});
1993
+
1994
+ if (options.expires) {
1995
+ utils.expires(options);
1996
+ }
1997
+
1998
+ this._indexes.push([fields, options]);
1999
+ return this;
2000
+ };
2001
+
2002
+ /**
2003
+ * Sets a schema option.
2004
+ *
2005
+ * #### Example:
2006
+ *
2007
+ * schema.set('strict'); // 'true' by default
2008
+ * schema.set('strict', false); // Sets 'strict' to false
2009
+ * schema.set('strict'); // 'false'
2010
+ *
2011
+ * @param {String} key The name of the option to set the value to
2012
+ * @param {Object} [value] The value to set the option to, if not passed, the option will be reset to default
2013
+ * @see Schema #schema_Schema
2014
+ * @api public
2015
+ */
2016
+
2017
+ Schema.prototype.set = function(key, value, _tags) {
2018
+ if (arguments.length === 1) {
2019
+ return this.options[key];
2020
+ }
2021
+
2022
+ switch (key) {
2023
+ case 'read':
2024
+ this.options[key] = readPref(value, _tags);
2025
+ this._userProvidedOptions[key] = this.options[key];
2026
+ break;
2027
+ case 'timestamps':
2028
+ this.setupTimestamp(value);
2029
+ this.options[key] = value;
2030
+ this._userProvidedOptions[key] = this.options[key];
2031
+ break;
2032
+ case '_id':
2033
+ this.options[key] = value;
2034
+ this._userProvidedOptions[key] = this.options[key];
2035
+
2036
+ if (value && !this.paths['_id']) {
2037
+ addAutoId(this);
2038
+ } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) {
2039
+ this.remove('_id');
2040
+ }
2041
+ break;
2042
+ default:
2043
+ this.options[key] = value;
2044
+ this._userProvidedOptions[key] = this.options[key];
2045
+ break;
2046
+ }
2047
+
2048
+ return this;
2049
+ };
2050
+
2051
+ /**
2052
+ * Gets a schema option.
2053
+ *
2054
+ * #### Example:
2055
+ *
2056
+ * schema.get('strict'); // true
2057
+ * schema.set('strict', false);
2058
+ * schema.get('strict'); // false
2059
+ *
2060
+ * @param {String} key The name of the Option to get the current value for
2061
+ * @api public
2062
+ * @return {Any} the option's value
2063
+ */
2064
+
2065
+ Schema.prototype.get = function(key) {
2066
+ return this.options[key];
2067
+ };
2068
+
2069
+ const indexTypes = '2d 2dsphere hashed text'.split(' ');
2070
+
2071
+ /**
2072
+ * The allowed index types
2073
+ *
2074
+ * @property {String[]} indexTypes
2075
+ * @memberOf Schema
2076
+ * @static
2077
+ * @api public
2078
+ */
2079
+
2080
+ Object.defineProperty(Schema, 'indexTypes', {
2081
+ get: function() {
2082
+ return indexTypes;
2083
+ },
2084
+ set: function() {
2085
+ throw new Error('Cannot overwrite Schema.indexTypes');
2086
+ }
2087
+ });
2088
+
2089
+ /**
2090
+ * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
2091
+ * Indexes are expressed as an array `[spec, options]`.
2092
+ *
2093
+ * #### Example:
2094
+ *
2095
+ * const userSchema = new Schema({
2096
+ * email: { type: String, required: true, unique: true },
2097
+ * registeredAt: { type: Date, index: true }
2098
+ * });
2099
+ *
2100
+ * // [ [ { email: 1 }, { unique: true, background: true } ],
2101
+ * // [ { registeredAt: 1 }, { background: true } ] ]
2102
+ * userSchema.indexes();
2103
+ *
2104
+ * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
2105
+ * For example, the below plugin makes every index unique by default.
2106
+ *
2107
+ * function myPlugin(schema) {
2108
+ * for (const index of schema.indexes()) {
2109
+ * if (index[1].unique === undefined) {
2110
+ * index[1].unique = true;
2111
+ * }
2112
+ * }
2113
+ * }
2114
+ *
2115
+ * @api public
2116
+ * @return {Array} list of indexes defined in the schema
2117
+ */
2118
+
2119
+ Schema.prototype.indexes = function() {
2120
+ return getIndexes(this);
2121
+ };
2122
+
2123
+ /**
2124
+ * Creates a virtual type with the given name.
2125
+ *
2126
+ * @param {String} name The name of the Virtual
2127
+ * @param {Object} [options]
2128
+ * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](/docs/populate.html#populate-virtuals).
2129
+ * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information.
2130
+ * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information.
2131
+ * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
2132
+ * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
2133
+ * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc.
2134
+ * @return {VirtualType}
2135
+ */
2136
+
2137
+ Schema.prototype.virtual = function(name, options) {
2138
+ if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2139
+ return this.virtual(name.path, name.options);
2140
+ }
2141
+ options = new VirtualOptions(options);
2142
+
2143
+ if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
2144
+ if (options.localField == null) {
2145
+ throw new Error('Reference virtuals require `localField` option');
2146
+ }
2147
+
2148
+ if (options.foreignField == null) {
2149
+ throw new Error('Reference virtuals require `foreignField` option');
2150
+ }
2151
+
2152
+ this.pre('init', function virtualPreInit(obj) {
2153
+ if (mpath.has(name, obj)) {
2154
+ const _v = mpath.get(name, obj);
2155
+ if (!this.$$populatedVirtuals) {
2156
+ this.$$populatedVirtuals = {};
2157
+ }
2158
+
2159
+ if (options.justOne || options.count) {
2160
+ this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2161
+ _v[0] :
2162
+ _v;
2163
+ } else {
2164
+ this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2165
+ _v :
2166
+ _v == null ? [] : [_v];
2167
+ }
2168
+
2169
+ mpath.unset(name, obj);
2170
+ }
2171
+ });
2172
+
2173
+ const virtual = this.virtual(name);
2174
+ virtual.options = options;
2175
+
2176
+ virtual.
2177
+ set(function(_v) {
2178
+ if (!this.$$populatedVirtuals) {
2179
+ this.$$populatedVirtuals = {};
2180
+ }
2181
+
2182
+ if (options.justOne || options.count) {
2183
+ this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2184
+ _v[0] :
2185
+ _v;
2186
+
2187
+ if (typeof this.$$populatedVirtuals[name] !== 'object') {
2188
+ this.$$populatedVirtuals[name] = options.count ? _v : null;
2189
+ }
2190
+ } else {
2191
+ this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2192
+ _v :
2193
+ _v == null ? [] : [_v];
2194
+
2195
+ this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
2196
+ return doc && typeof doc === 'object';
2197
+ });
2198
+ }
2199
+ });
2200
+
2201
+ if (typeof options.get === 'function') {
2202
+ virtual.get(options.get);
2203
+ }
2204
+
2205
+ // Workaround for gh-8198: if virtual is under document array, make a fake
2206
+ // virtual. See gh-8210
2207
+ const parts = name.split('.');
2208
+ let cur = parts[0];
2209
+ for (let i = 0; i < parts.length - 1; ++i) {
2210
+ if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) {
2211
+ const remnant = parts.slice(i + 1).join('.');
2212
+ this.paths[cur].schema.virtual(remnant, options);
2213
+ break;
2214
+ }
2215
+
2216
+ cur += '.' + parts[i + 1];
2217
+ }
2218
+
2219
+ return virtual;
2220
+ }
2221
+
2222
+ const virtuals = this.virtuals;
2223
+ const parts = name.split('.');
2224
+
2225
+ if (this.pathType(name) === 'real') {
2226
+ throw new Error('Virtual path "' + name + '"' +
2227
+ ' conflicts with a real path in the schema');
2228
+ }
2229
+
2230
+ virtuals[name] = parts.reduce(function(mem, part, i) {
2231
+ mem[part] || (mem[part] = (i === parts.length - 1)
2232
+ ? new VirtualType(options, name)
2233
+ : {});
2234
+ return mem[part];
2235
+ }, this.tree);
2236
+
2237
+ return virtuals[name];
2238
+ };
2239
+
2240
+ /**
2241
+ * Returns the virtual type with the given `name`.
2242
+ *
2243
+ * @param {String} name The name of the Virtual to get
2244
+ * @return {VirtualType|null}
2245
+ */
2246
+
2247
+ Schema.prototype.virtualpath = function(name) {
2248
+ return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
2249
+ };
2250
+
2251
+ /**
2252
+ * Removes the given `path` (or [`paths`]).
2253
+ *
2254
+ * #### Example:
2255
+ *
2256
+ * const schema = new Schema({ name: String, age: Number });
2257
+ * schema.remove('name');
2258
+ * schema.path('name'); // Undefined
2259
+ * schema.path('age'); // SchemaNumber { ... }
2260
+ *
2261
+ * Or as a Array:
2262
+ *
2263
+ * schema.remove(['name', 'age']);
2264
+ * schema.path('name'); // Undefined
2265
+ * schema.path('age'); // Undefined
2266
+ *
2267
+ * @param {String|Array} path The Path(s) to remove
2268
+ * @return {Schema} the Schema instance
2269
+ * @api public
2270
+ */
2271
+ Schema.prototype.remove = function(path) {
2272
+ if (typeof path === 'string') {
2273
+ path = [path];
2274
+ }
2275
+ if (Array.isArray(path)) {
2276
+ path.forEach(function(name) {
2277
+ if (this.path(name) == null && !this.nested[name]) {
2278
+ return;
2279
+ }
2280
+ if (this.nested[name]) {
2281
+ const allKeys = Object.keys(this.paths).
2282
+ concat(Object.keys(this.nested));
2283
+ for (const path of allKeys) {
2284
+ if (path.startsWith(name + '.')) {
2285
+ delete this.paths[path];
2286
+ delete this.nested[path];
2287
+ _deletePath(this, path);
2288
+ }
2289
+ }
2290
+
2291
+ delete this.nested[name];
2292
+ _deletePath(this, name);
2293
+ return;
2294
+ }
2295
+
2296
+ delete this.paths[name];
2297
+ _deletePath(this, name);
2298
+ }, this);
2299
+ }
2300
+ return this;
2301
+ };
2302
+
2303
+ /*!
2304
+ * ignore
2305
+ */
2306
+
2307
+ function _deletePath(schema, name) {
2308
+ const pieces = name.split('.');
2309
+ const last = pieces.pop();
2310
+
2311
+ let branch = schema.tree;
2312
+
2313
+ for (const piece of pieces) {
2314
+ branch = branch[piece];
2315
+ }
2316
+
2317
+ delete branch[last];
2318
+ }
2319
+
2320
+ /**
2321
+ * Removes the given virtual or virtuals from the schema.
2322
+ *
2323
+ * @param {String|Array} path The virutal path(s) to remove.
2324
+ * @returns {Schema} the Schema instance, or a mongoose error if the virtual does not exist.
2325
+ * @api public
2326
+ */
2327
+
2328
+ Schema.prototype.removeVirtual = function(path) {
2329
+ if (typeof path === 'string') {
2330
+ path = [path];
2331
+ }
2332
+ if (Array.isArray(path)) {
2333
+ for (const virtual of path) {
2334
+ if (this.virtuals[virtual] == null) {
2335
+ throw new MongooseError(`Attempting to remove virtual "${virtual}" that does not exist.`);
2336
+ }
2337
+ }
2338
+
2339
+ for (const virtual of path) {
2340
+ delete this.paths[virtual];
2341
+ delete this.virtuals[virtual];
2342
+ if (virtual.indexOf('.') !== -1) {
2343
+ mpath.unset(virtual, this.tree);
2344
+ } else {
2345
+ delete this.tree[virtual];
2346
+ }
2347
+ }
2348
+ }
2349
+ return this;
2350
+ };
2351
+
2352
+ /**
2353
+ * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
2354
+ * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
2355
+ * to schema [virtuals](/docs/guide.html#virtuals),
2356
+ * [statics](/docs/guide.html#statics), and
2357
+ * [methods](/docs/guide.html#methods).
2358
+ *
2359
+ * #### Example:
2360
+ *
2361
+ * ```javascript
2362
+ * const md5 = require('md5');
2363
+ * const userSchema = new Schema({ email: String });
2364
+ * class UserClass {
2365
+ * // `gravatarImage` becomes a virtual
2366
+ * get gravatarImage() {
2367
+ * const hash = md5(this.email.toLowerCase());
2368
+ * return `https://www.gravatar.com/avatar/${hash}`;
2369
+ * }
2370
+ *
2371
+ * // `getProfileUrl()` becomes a document method
2372
+ * getProfileUrl() {
2373
+ * return `https://mysite.com/${this.email}`;
2374
+ * }
2375
+ *
2376
+ * // `findByEmail()` becomes a static
2377
+ * static findByEmail(email) {
2378
+ * return this.findOne({ email });
2379
+ * }
2380
+ * }
2381
+ *
2382
+ * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
2383
+ * // and a `findByEmail()` static
2384
+ * userSchema.loadClass(UserClass);
2385
+ * ```
2386
+ *
2387
+ * @param {Function} model The Class to load
2388
+ * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
2389
+ */
2390
+ Schema.prototype.loadClass = function(model, virtualsOnly) {
2391
+ // Stop copying when hit certain base classes
2392
+ if (model === Object.prototype ||
2393
+ model === Function.prototype ||
2394
+ model.prototype.hasOwnProperty('$isMongooseModelPrototype') ||
2395
+ model.prototype.hasOwnProperty('$isMongooseDocumentPrototype')) {
2396
+ return this;
2397
+ }
2398
+
2399
+ this.loadClass(Object.getPrototypeOf(model), virtualsOnly);
2400
+
2401
+ // Add static methods
2402
+ if (!virtualsOnly) {
2403
+ Object.getOwnPropertyNames(model).forEach(function(name) {
2404
+ if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) {
2405
+ return;
2406
+ }
2407
+ const prop = Object.getOwnPropertyDescriptor(model, name);
2408
+ if (prop.hasOwnProperty('value')) {
2409
+ this.static(name, prop.value);
2410
+ }
2411
+ }, this);
2412
+ }
2413
+
2414
+ // Add methods and virtuals
2415
+ Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
2416
+ if (name.match(/^(constructor)$/)) {
2417
+ return;
2418
+ }
2419
+ const method = Object.getOwnPropertyDescriptor(model.prototype, name);
2420
+ if (!virtualsOnly) {
2421
+ if (typeof method.value === 'function') {
2422
+ this.method(name, method.value);
2423
+ }
2424
+ }
2425
+ if (typeof method.get === 'function') {
2426
+ if (this.virtuals[name]) {
2427
+ this.virtuals[name].getters = [];
2428
+ }
2429
+ this.virtual(name).get(method.get);
2430
+ }
2431
+ if (typeof method.set === 'function') {
2432
+ if (this.virtuals[name]) {
2433
+ this.virtuals[name].setters = [];
2434
+ }
2435
+ this.virtual(name).set(method.set);
2436
+ }
2437
+ }, this);
2438
+
2439
+ return this;
2440
+ };
2441
+
2442
+ /*!
2443
+ * ignore
2444
+ */
2445
+
2446
+ Schema.prototype._getSchema = function(path) {
2447
+ const _this = this;
2448
+ const pathschema = _this.path(path);
2449
+ const resultPath = [];
2450
+
2451
+ if (pathschema) {
2452
+ pathschema.$fullPath = path;
2453
+ return pathschema;
2454
+ }
2455
+
2456
+ function search(parts, schema) {
2457
+ let p = parts.length + 1;
2458
+ let foundschema;
2459
+ let trypath;
2460
+
2461
+ while (p--) {
2462
+ trypath = parts.slice(0, p).join('.');
2463
+ foundschema = schema.path(trypath);
2464
+ if (foundschema) {
2465
+ resultPath.push(trypath);
2466
+
2467
+ if (foundschema.caster) {
2468
+ // array of Mixed?
2469
+ if (foundschema.caster instanceof MongooseTypes.Mixed) {
2470
+ foundschema.caster.$fullPath = resultPath.join('.');
2471
+ return foundschema.caster;
2472
+ }
2473
+
2474
+ // Now that we found the array, we need to check if there
2475
+ // are remaining document paths to look up for casting.
2476
+ // Also we need to handle array.$.path since schema.path
2477
+ // doesn't work for that.
2478
+ // If there is no foundschema.schema we are dealing with
2479
+ // a path like array.$
2480
+ if (p !== parts.length) {
2481
+ if (foundschema.schema) {
2482
+ let ret;
2483
+ if (parts[p] === '$' || isArrayFilter(parts[p])) {
2484
+ if (p + 1 === parts.length) {
2485
+ // comments.$
2486
+ return foundschema;
2487
+ }
2488
+ // comments.$.comments.$.title
2489
+ ret = search(parts.slice(p + 1), foundschema.schema);
2490
+ if (ret) {
2491
+ ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
2492
+ !foundschema.schema.$isSingleNested;
2493
+ }
2494
+ return ret;
2495
+ }
2496
+ // this is the last path of the selector
2497
+ ret = search(parts.slice(p), foundschema.schema);
2498
+ if (ret) {
2499
+ ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
2500
+ !foundschema.schema.$isSingleNested;
2501
+ }
2502
+ return ret;
2503
+ }
2504
+ }
2505
+ } else if (foundschema.$isSchemaMap) {
2506
+ if (p >= parts.length) {
2507
+ return foundschema;
2508
+ }
2509
+ // Any path in the map will be an instance of the map's embedded schematype
2510
+ if (p + 1 >= parts.length) {
2511
+ return foundschema.$__schemaType;
2512
+ }
2513
+
2514
+ if (foundschema.$__schemaType instanceof MongooseTypes.Mixed) {
2515
+ return foundschema.$__schemaType;
2516
+ }
2517
+ if (foundschema.$__schemaType.schema != null) {
2518
+ // Map of docs
2519
+ const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema);
2520
+ return ret;
2521
+ }
2522
+ }
2523
+
2524
+ foundschema.$fullPath = resultPath.join('.');
2525
+
2526
+ return foundschema;
2527
+ }
2528
+ }
2529
+ }
2530
+
2531
+ // look for arrays
2532
+ const parts = path.split('.');
2533
+ for (let i = 0; i < parts.length; ++i) {
2534
+ if (parts[i] === '$' || isArrayFilter(parts[i])) {
2535
+ // Re: gh-5628, because `schema.path()` doesn't take $ into account.
2536
+ parts[i] = '0';
2537
+ }
2538
+ }
2539
+ return search(parts, _this);
2540
+ };
2541
+
2542
+ /*!
2543
+ * ignore
2544
+ */
2545
+
2546
+ Schema.prototype._getPathType = function(path) {
2547
+ const _this = this;
2548
+ const pathschema = _this.path(path);
2549
+
2550
+ if (pathschema) {
2551
+ return 'real';
2552
+ }
2553
+
2554
+ function search(parts, schema) {
2555
+ let p = parts.length + 1,
2556
+ foundschema,
2557
+ trypath;
2558
+
2559
+ while (p--) {
2560
+ trypath = parts.slice(0, p).join('.');
2561
+ foundschema = schema.path(trypath);
2562
+ if (foundschema) {
2563
+ if (foundschema.caster) {
2564
+ // array of Mixed?
2565
+ if (foundschema.caster instanceof MongooseTypes.Mixed) {
2566
+ return { schema: foundschema, pathType: 'mixed' };
2567
+ }
2568
+
2569
+ // Now that we found the array, we need to check if there
2570
+ // are remaining document paths to look up for casting.
2571
+ // Also we need to handle array.$.path since schema.path
2572
+ // doesn't work for that.
2573
+ // If there is no foundschema.schema we are dealing with
2574
+ // a path like array.$
2575
+ if (p !== parts.length && foundschema.schema) {
2576
+ if (parts[p] === '$' || isArrayFilter(parts[p])) {
2577
+ if (p === parts.length - 1) {
2578
+ return { schema: foundschema, pathType: 'nested' };
2579
+ }
2580
+ // comments.$.comments.$.title
2581
+ return search(parts.slice(p + 1), foundschema.schema);
2582
+ }
2583
+ // this is the last path of the selector
2584
+ return search(parts.slice(p), foundschema.schema);
2585
+ }
2586
+ return {
2587
+ schema: foundschema,
2588
+ pathType: foundschema.$isSingleNested ? 'nested' : 'array'
2589
+ };
2590
+ }
2591
+ return { schema: foundschema, pathType: 'real' };
2592
+ } else if (p === parts.length && schema.nested[trypath]) {
2593
+ return { schema: schema, pathType: 'nested' };
2594
+ }
2595
+ }
2596
+ return { schema: foundschema || schema, pathType: 'undefined' };
2597
+ }
2598
+
2599
+ // look for arrays
2600
+ return search(path.split('.'), _this);
2601
+ };
2602
+
2603
+ /*!
2604
+ * ignore
2605
+ */
2606
+
2607
+ function isArrayFilter(piece) {
2608
+ return piece.startsWith('$[') && piece.endsWith(']');
2609
+ }
2610
+
2611
+ /**
2612
+ * Called by `compile()` _right before_ compiling. Good for making any changes to
2613
+ * the schema that should respect options set by plugins, like `id`
2614
+ * @method _preCompile
2615
+ * @memberOf Schema
2616
+ * @instance
2617
+ * @api private
2618
+ */
2619
+
2620
+ Schema.prototype._preCompile = function _preCompile() {
2621
+ idGetter(this);
2622
+ };
2623
+
2624
+ /*!
2625
+ * Module exports.
2626
+ */
2627
+
2628
+ module.exports = exports = Schema;
2629
+
2630
+ // require down here because of reference issues
2631
+
2632
+ /**
2633
+ * The various built-in Mongoose Schema Types.
2634
+ *
2635
+ * #### Example:
2636
+ *
2637
+ * const mongoose = require('mongoose');
2638
+ * const ObjectId = mongoose.Schema.Types.ObjectId;
2639
+ *
2640
+ * #### Types:
2641
+ *
2642
+ * - [String](/docs/schematypes.html#strings)
2643
+ * - [Number](/docs/schematypes.html#numbers)
2644
+ * - [Boolean](/docs/schematypes.html#booleans) | Bool
2645
+ * - [Array](/docs/schematypes.html#arrays)
2646
+ * - [Buffer](/docs/schematypes.html#buffers)
2647
+ * - [Date](/docs/schematypes.html#dates)
2648
+ * - [ObjectId](/docs/schematypes.html#objectids) | Oid
2649
+ * - [Mixed](/docs/schematypes.html#mixed)
2650
+ *
2651
+ * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
2652
+ *
2653
+ * const Mixed = mongoose.Schema.Types.Mixed;
2654
+ * new mongoose.Schema({ _user: Mixed })
2655
+ *
2656
+ * @api public
2657
+ */
2658
+
2659
+ Schema.Types = MongooseTypes = require('./schema/index');
2660
+
2661
+ /*!
2662
+ * ignore
2663
+ */
2664
+
2665
+ exports.ObjectId = MongooseTypes.ObjectId;