@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
@@ -0,0 +1,1727 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const MongooseError = require('./error/index');
8
+ const SchemaTypeOptions = require('./options/SchemaTypeOptions');
9
+ const $exists = require('./schema/operators/exists');
10
+ const $type = require('./schema/operators/type');
11
+ const handleImmutable = require('./helpers/schematype/handleImmutable');
12
+ const isAsyncFunction = require('./helpers/isAsyncFunction');
13
+ const isSimpleValidator = require('./helpers/isSimpleValidator');
14
+ const immediate = require('./helpers/immediate');
15
+ const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
16
+ const utils = require('./utils');
17
+ const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol;
18
+ const documentIsModified = require('./helpers/symbols').documentIsModified;
19
+
20
+ const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
21
+
22
+ const CastError = MongooseError.CastError;
23
+ const ValidatorError = MongooseError.ValidatorError;
24
+
25
+ const setOptionsForDefaults = { _skipMarkModified: true };
26
+
27
+ /**
28
+ * SchemaType constructor. Do **not** instantiate `SchemaType` directly.
29
+ * Mongoose converts your schema paths into SchemaTypes automatically.
30
+ *
31
+ * #### Example:
32
+ *
33
+ * const schema = new Schema({ name: String });
34
+ * schema.path('name') instanceof SchemaType; // true
35
+ *
36
+ * @param {String} path
37
+ * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html)
38
+ * @param {String} [instance]
39
+ * @api public
40
+ */
41
+
42
+ function SchemaType(path, options, instance) {
43
+ this[schemaTypeSymbol] = true;
44
+ this.path = path;
45
+ this.instance = instance;
46
+ this.validators = [];
47
+ this.getters = this.constructor.hasOwnProperty('getters') ?
48
+ this.constructor.getters.slice() :
49
+ [];
50
+ this.setters = [];
51
+
52
+ this.splitPath();
53
+
54
+ options = options || {};
55
+ const defaultOptions = this.constructor.defaultOptions || {};
56
+ const defaultOptionsKeys = Object.keys(defaultOptions);
57
+
58
+ for (const option of defaultOptionsKeys) {
59
+ if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
60
+ options[option] = defaultOptions[option];
61
+ }
62
+ }
63
+
64
+ if (options.select == null) {
65
+ delete options.select;
66
+ }
67
+
68
+ const Options = this.OptionsConstructor || SchemaTypeOptions;
69
+ this.options = new Options(options);
70
+ this._index = null;
71
+
72
+
73
+ if (utils.hasUserDefinedProperty(this.options, 'immutable')) {
74
+ this.$immutable = this.options.immutable;
75
+
76
+ handleImmutable(this);
77
+ }
78
+
79
+ const keys = Object.keys(this.options);
80
+ for (const prop of keys) {
81
+ if (prop === 'cast') {
82
+ this.castFunction(this.options[prop]);
83
+ continue;
84
+ }
85
+ if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') {
86
+ // { unique: true, index: true }
87
+ if (prop === 'index' && this._index) {
88
+ if (options.index === false) {
89
+ const index = this._index;
90
+ if (typeof index === 'object' && index != null) {
91
+ if (index.unique) {
92
+ throw new Error('Path "' + this.path + '" may not have `index` ' +
93
+ 'set to false and `unique` set to true');
94
+ }
95
+ if (index.sparse) {
96
+ throw new Error('Path "' + this.path + '" may not have `index` ' +
97
+ 'set to false and `sparse` set to true');
98
+ }
99
+ }
100
+
101
+ this._index = false;
102
+ }
103
+ continue;
104
+ }
105
+
106
+ const val = options[prop];
107
+ // Special case so we don't screw up array defaults, see gh-5780
108
+ if (prop === 'default') {
109
+ this.default(val);
110
+ continue;
111
+ }
112
+
113
+ const opts = Array.isArray(val) ? val : [val];
114
+
115
+ this[prop].apply(this, opts);
116
+ }
117
+ }
118
+
119
+ Object.defineProperty(this, '$$context', {
120
+ enumerable: false,
121
+ configurable: false,
122
+ writable: true,
123
+ value: null
124
+ });
125
+ }
126
+
127
+ /**
128
+ * The class that Mongoose uses internally to instantiate this SchemaType's `options` property.
129
+ * @memberOf SchemaType
130
+ * @instance
131
+ * @api private
132
+ */
133
+
134
+ SchemaType.prototype.OptionsConstructor = SchemaTypeOptions;
135
+
136
+ /**
137
+ * The path to this SchemaType in a Schema.
138
+ *
139
+ * #### Example:
140
+ *
141
+ * const schema = new Schema({ name: String });
142
+ * schema.path('name').path; // 'name'
143
+ *
144
+ * @property path
145
+ * @api public
146
+ * @memberOf SchemaType
147
+ */
148
+
149
+ SchemaType.prototype.path;
150
+
151
+ /**
152
+ * The validators that Mongoose should run to validate properties at this SchemaType's path.
153
+ *
154
+ * #### Example:
155
+ *
156
+ * const schema = new Schema({ name: { type: String, required: true } });
157
+ * schema.path('name').validators.length; // 1, the `required` validator
158
+ *
159
+ * @property validators
160
+ * @api public
161
+ * @memberOf SchemaType
162
+ */
163
+
164
+ SchemaType.prototype.validators;
165
+
166
+ /**
167
+ * True if this SchemaType has a required validator. False otherwise.
168
+ *
169
+ * #### Example:
170
+ *
171
+ * const schema = new Schema({ name: { type: String, required: true } });
172
+ * schema.path('name').isRequired; // true
173
+ *
174
+ * schema.path('name').required(false);
175
+ * schema.path('name').isRequired; // false
176
+ *
177
+ * @property isRequired
178
+ * @api public
179
+ * @memberOf SchemaType
180
+ */
181
+
182
+ SchemaType.prototype.isRequired;
183
+
184
+ /**
185
+ * Split the current dottet path into segments
186
+ *
187
+ * @return {String[]|undefined}
188
+ * @api private
189
+ */
190
+
191
+ SchemaType.prototype.splitPath = function() {
192
+ if (this._presplitPath != null) {
193
+ return this._presplitPath;
194
+ }
195
+ if (this.path == null) {
196
+ return undefined;
197
+ }
198
+
199
+ this._presplitPath = this.path.indexOf('.') === -1 ? [this.path] : this.path.split('.');
200
+ return this._presplitPath;
201
+ };
202
+
203
+ /**
204
+ * Get/set the function used to cast arbitrary values to this type.
205
+ *
206
+ * #### Example:
207
+ *
208
+ * // Disallow `null` for numbers, and don't try to cast any values to
209
+ * // numbers, so even strings like '123' will cause a CastError.
210
+ * mongoose.Number.cast(function(v) {
211
+ * assert.ok(v === undefined || typeof v === 'number');
212
+ * return v;
213
+ * });
214
+ *
215
+ * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed
216
+ * @return {Function}
217
+ * @static
218
+ * @memberOf SchemaType
219
+ * @function cast
220
+ * @api public
221
+ */
222
+
223
+ SchemaType.cast = function cast(caster) {
224
+ if (arguments.length === 0) {
225
+ return this._cast;
226
+ }
227
+ if (caster === false) {
228
+ caster = v => v;
229
+ }
230
+ this._cast = caster;
231
+
232
+ return this._cast;
233
+ };
234
+
235
+ /**
236
+ * Get/set the function used to cast arbitrary values to this particular schematype instance.
237
+ * Overrides `SchemaType.cast()`.
238
+ *
239
+ * #### Example:
240
+ *
241
+ * // Disallow `null` for numbers, and don't try to cast any values to
242
+ * // numbers, so even strings like '123' will cause a CastError.
243
+ * const number = new mongoose.Number('mypath', {});
244
+ * number.cast(function(v) {
245
+ * assert.ok(v === undefined || typeof v === 'number');
246
+ * return v;
247
+ * });
248
+ *
249
+ * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed
250
+ * @return {Function}
251
+ * @memberOf SchemaType
252
+ * @api public
253
+ */
254
+
255
+ SchemaType.prototype.castFunction = function castFunction(caster) {
256
+ if (arguments.length === 0) {
257
+ return this._castFunction;
258
+ }
259
+ if (caster === false) {
260
+ caster = this.constructor._defaultCaster || (v => v);
261
+ }
262
+ this._castFunction = caster;
263
+
264
+ return this._castFunction;
265
+ };
266
+
267
+ /**
268
+ * The function that Mongoose calls to cast arbitrary values to this SchemaType.
269
+ *
270
+ * @param {Object} value value to cast
271
+ * @param {Document} doc document that triggers the casting
272
+ * @param {Boolean} init
273
+ * @api public
274
+ */
275
+
276
+ SchemaType.prototype.cast = function cast() {
277
+ throw new Error('Base SchemaType class does not implement a `cast()` function');
278
+ };
279
+
280
+ /**
281
+ * Sets a default option for this schema type.
282
+ *
283
+ * #### Example:
284
+ *
285
+ * // Make all strings be trimmed by default
286
+ * mongoose.SchemaTypes.String.set('trim', true);
287
+ *
288
+ * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...)
289
+ * @param {Any} value The value of the option you'd like to set.
290
+ * @return {void}
291
+ * @static
292
+ * @memberOf SchemaType
293
+ * @function set
294
+ * @api public
295
+ */
296
+
297
+ SchemaType.set = function set(option, value) {
298
+ if (!this.hasOwnProperty('defaultOptions')) {
299
+ this.defaultOptions = Object.assign({}, this.defaultOptions);
300
+ }
301
+ this.defaultOptions[option] = value;
302
+ };
303
+
304
+ /**
305
+ * Attaches a getter for all instances of this schema type.
306
+ *
307
+ * #### Example:
308
+ *
309
+ * // Make all numbers round down
310
+ * mongoose.Number.get(function(v) { return Math.floor(v); });
311
+ *
312
+ * @param {Function} getter
313
+ * @return {this}
314
+ * @static
315
+ * @memberOf SchemaType
316
+ * @function get
317
+ * @api public
318
+ */
319
+
320
+ SchemaType.get = function(getter) {
321
+ this.getters = this.hasOwnProperty('getters') ? this.getters : [];
322
+ this.getters.push(getter);
323
+ };
324
+
325
+ /**
326
+ * Sets a default value for this SchemaType.
327
+ *
328
+ * #### Example:
329
+ *
330
+ * const schema = new Schema({ n: { type: Number, default: 10 })
331
+ * const M = db.model('M', schema)
332
+ * const m = new M;
333
+ * console.log(m.n) // 10
334
+ *
335
+ * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.
336
+ *
337
+ * #### Example:
338
+ *
339
+ * // values are cast:
340
+ * const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
341
+ * const M = db.model('M', schema)
342
+ * const m = new M;
343
+ * console.log(m.aNumber) // 4.815162342
344
+ *
345
+ * // default unique objects for Mixed types:
346
+ * const schema = new Schema({ mixed: Schema.Types.Mixed });
347
+ * schema.path('mixed').default(function () {
348
+ * return {};
349
+ * });
350
+ *
351
+ * // if we don't use a function to return object literals for Mixed defaults,
352
+ * // each document will receive a reference to the same object literal creating
353
+ * // a "shared" object instance:
354
+ * const schema = new Schema({ mixed: Schema.Types.Mixed });
355
+ * schema.path('mixed').default({});
356
+ * const M = db.model('M', schema);
357
+ * const m1 = new M;
358
+ * m1.mixed.added = 1;
359
+ * console.log(m1.mixed); // { added: 1 }
360
+ * const m2 = new M;
361
+ * console.log(m2.mixed); // { added: 1 }
362
+ *
363
+ * @param {Function|any} val The default value to set
364
+ * @return {Any|undefined} Returns the set default value.
365
+ * @api public
366
+ */
367
+
368
+ SchemaType.prototype.default = function(val) {
369
+ if (arguments.length === 1) {
370
+ if (val === void 0) {
371
+ this.defaultValue = void 0;
372
+ return void 0;
373
+ }
374
+
375
+ if (val != null && val.instanceOfSchema) {
376
+ throw new MongooseError('Cannot set default value of path `' + this.path +
377
+ '` to a mongoose Schema instance.');
378
+ }
379
+
380
+ this.defaultValue = val;
381
+ return this.defaultValue;
382
+ } else if (arguments.length > 1) {
383
+ this.defaultValue = [...arguments];
384
+ }
385
+ return this.defaultValue;
386
+ };
387
+
388
+ /**
389
+ * Declares the index options for this schematype.
390
+ *
391
+ * #### Example:
392
+ *
393
+ * const s = new Schema({ name: { type: String, index: true })
394
+ * const s = new Schema({ name: { type: String, index: -1 })
395
+ * const s = new Schema({ loc: { type: [Number], index: 'hashed' })
396
+ * const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
397
+ * const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
398
+ * const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
399
+ * s.path('my.path').index(true);
400
+ * s.path('my.date').index({ expires: 60 });
401
+ * s.path('my.path').index({ unique: true, sparse: true });
402
+ *
403
+ * #### Note:
404
+ *
405
+ * _Indexes are created [in the background](https://www.mongodb.com/docs/manual/core/index-creation/#index-creation-background)
406
+ * by default. If `background` is set to `false`, MongoDB will not execute any
407
+ * read/write operations you send until the index build.
408
+ * Specify `background: false` to override Mongoose's default._
409
+ *
410
+ * @param {Object|Boolean|String|Number} options
411
+ * @return {SchemaType} this
412
+ * @api public
413
+ */
414
+
415
+ SchemaType.prototype.index = function(options) {
416
+ this._index = options;
417
+ utils.expires(this._index);
418
+ return this;
419
+ };
420
+
421
+ /**
422
+ * Declares an unique index.
423
+ *
424
+ * #### Example:
425
+ *
426
+ * const s = new Schema({ name: { type: String, unique: true } });
427
+ * s.path('name').index({ unique: true });
428
+ *
429
+ * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
430
+ *
431
+ * @param {Boolean} bool
432
+ * @return {SchemaType} this
433
+ * @api public
434
+ */
435
+
436
+ SchemaType.prototype.unique = function(bool) {
437
+ if (this._index === false) {
438
+ if (!bool) {
439
+ return;
440
+ }
441
+ throw new Error('Path "' + this.path + '" may not have `index` set to ' +
442
+ 'false and `unique` set to true');
443
+ }
444
+
445
+ if (!this.options.hasOwnProperty('index') && bool === false) {
446
+ return this;
447
+ }
448
+
449
+ if (this._index == null || this._index === true) {
450
+ this._index = {};
451
+ } else if (typeof this._index === 'string') {
452
+ this._index = { type: this._index };
453
+ }
454
+
455
+ this._index.unique = bool;
456
+ return this;
457
+ };
458
+
459
+ /**
460
+ * Declares a full text index.
461
+ *
462
+ * ### Example:
463
+ *
464
+ * const s = new Schema({ name : { type: String, text : true } })
465
+ * s.path('name').index({ text : true });
466
+ *
467
+ * @param {Boolean} bool
468
+ * @return {SchemaType} this
469
+ * @api public
470
+ */
471
+
472
+ SchemaType.prototype.text = function(bool) {
473
+ if (this._index === false) {
474
+ if (!bool) {
475
+ return this;
476
+ }
477
+ throw new Error('Path "' + this.path + '" may not have `index` set to ' +
478
+ 'false and `text` set to true');
479
+ }
480
+
481
+ if (!this.options.hasOwnProperty('index') && bool === false) {
482
+ return this;
483
+ }
484
+
485
+ if (this._index === null || this._index === undefined ||
486
+ typeof this._index === 'boolean') {
487
+ this._index = {};
488
+ } else if (typeof this._index === 'string') {
489
+ this._index = { type: this._index };
490
+ }
491
+
492
+ this._index.text = bool;
493
+ return this;
494
+ };
495
+
496
+ /**
497
+ * Declares a sparse index.
498
+ *
499
+ * #### Example:
500
+ *
501
+ * const s = new Schema({ name: { type: String, sparse: true } });
502
+ * s.path('name').index({ sparse: true });
503
+ *
504
+ * @param {Boolean} bool
505
+ * @return {SchemaType} this
506
+ * @api public
507
+ */
508
+
509
+ SchemaType.prototype.sparse = function(bool) {
510
+ if (this._index === false) {
511
+ if (!bool) {
512
+ return this;
513
+ }
514
+ throw new Error('Path "' + this.path + '" may not have `index` set to ' +
515
+ 'false and `sparse` set to true');
516
+ }
517
+
518
+ if (!this.options.hasOwnProperty('index') && bool === false) {
519
+ return this;
520
+ }
521
+
522
+ if (this._index == null || typeof this._index === 'boolean') {
523
+ this._index = {};
524
+ } else if (typeof this._index === 'string') {
525
+ this._index = { type: this._index };
526
+ }
527
+
528
+ this._index.sparse = bool;
529
+ return this;
530
+ };
531
+
532
+ /**
533
+ * Defines this path as immutable. Mongoose prevents you from changing
534
+ * immutable paths unless the parent document has [`isNew: true`](/docs/api/document.html#document_Document-isNew).
535
+ *
536
+ * #### Example:
537
+ *
538
+ * const schema = new Schema({
539
+ * name: { type: String, immutable: true },
540
+ * age: Number
541
+ * });
542
+ * const Model = mongoose.model('Test', schema);
543
+ *
544
+ * await Model.create({ name: 'test' });
545
+ * const doc = await Model.findOne();
546
+ *
547
+ * doc.isNew; // false
548
+ * doc.name = 'new name';
549
+ * doc.name; // 'test', because `name` is immutable
550
+ *
551
+ * Mongoose also prevents changing immutable properties using `updateOne()`
552
+ * and `updateMany()` based on [strict mode](/docs/guide.html#strict).
553
+ *
554
+ * #### Example:
555
+ *
556
+ * // Mongoose will strip out the `name` update, because `name` is immutable
557
+ * Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
558
+ *
559
+ * // If `strict` is set to 'throw', Mongoose will throw an error if you
560
+ * // update `name`
561
+ * const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
562
+ * then(() => null, err => err);
563
+ * err.name; // StrictModeError
564
+ *
565
+ * // If `strict` is `false`, Mongoose allows updating `name` even though
566
+ * // the property is immutable.
567
+ * Model.updateOne({}, { name: 'test2' }, { strict: false });
568
+ *
569
+ * @param {Boolean} bool
570
+ * @return {SchemaType} this
571
+ * @see isNew /docs/api/document.html#document_Document-isNew
572
+ * @api public
573
+ */
574
+
575
+ SchemaType.prototype.immutable = function(bool) {
576
+ this.$immutable = bool;
577
+ handleImmutable(this);
578
+
579
+ return this;
580
+ };
581
+
582
+ /**
583
+ * Defines a custom function for transforming this path when converting a document to JSON.
584
+ *
585
+ * Mongoose calls this function with one parameter: the current `value` of the path. Mongoose
586
+ * then uses the return value in the JSON output.
587
+ *
588
+ * #### Example:
589
+ *
590
+ * const schema = new Schema({
591
+ * date: { type: Date, transform: v => v.getFullYear() }
592
+ * });
593
+ * const Model = mongoose.model('Test', schema);
594
+ *
595
+ * await Model.create({ date: new Date('2016-06-01') });
596
+ * const doc = await Model.findOne();
597
+ *
598
+ * doc.date instanceof Date; // true
599
+ *
600
+ * doc.toJSON().date; // 2016 as a number
601
+ * JSON.stringify(doc); // '{"_id":...,"date":2016}'
602
+ *
603
+ * @param {Function} fn
604
+ * @return {SchemaType} this
605
+ * @api public
606
+ */
607
+
608
+ SchemaType.prototype.transform = function(fn) {
609
+ this.options.transform = fn;
610
+
611
+ return this;
612
+ };
613
+
614
+ /**
615
+ * Adds a setter to this schematype.
616
+ *
617
+ * #### Example:
618
+ *
619
+ * function capitalize (val) {
620
+ * if (typeof val !== 'string') val = '';
621
+ * return val.charAt(0).toUpperCase() + val.substring(1);
622
+ * }
623
+ *
624
+ * // defining within the schema
625
+ * const s = new Schema({ name: { type: String, set: capitalize }});
626
+ *
627
+ * // or with the SchemaType
628
+ * const s = new Schema({ name: String })
629
+ * s.path('name').set(capitalize);
630
+ *
631
+ * Setters allow you to transform the data before it gets to the raw mongodb
632
+ * document or query.
633
+ *
634
+ * Suppose you are implementing user registration for a website. Users provide
635
+ * an email and password, which gets saved to mongodb. The email is a string
636
+ * that you will want to normalize to lower case, in order to avoid one email
637
+ * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM.
638
+ *
639
+ * You can set up email lower case normalization easily via a Mongoose setter.
640
+ *
641
+ * function toLower(v) {
642
+ * return v.toLowerCase();
643
+ * }
644
+ *
645
+ * const UserSchema = new Schema({
646
+ * email: { type: String, set: toLower }
647
+ * });
648
+ *
649
+ * const User = db.model('User', UserSchema);
650
+ *
651
+ * const user = new User({email: 'AVENUE@Q.COM'});
652
+ * console.log(user.email); // 'avenue@q.com'
653
+ *
654
+ * // or
655
+ * const user = new User();
656
+ * user.email = 'Avenue@Q.com';
657
+ * console.log(user.email); // 'avenue@q.com'
658
+ * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'
659
+ *
660
+ * As you can see above, setters allow you to transform the data before it
661
+ * stored in MongoDB, or before executing a query.
662
+ *
663
+ * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._
664
+ *
665
+ * new Schema({ email: { type: String, lowercase: true }})
666
+ *
667
+ * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.
668
+ *
669
+ * function inspector (val, priorValue, schematype) {
670
+ * if (schematype.options.required) {
671
+ * return schematype.path + ' is required';
672
+ * } else {
673
+ * return val;
674
+ * }
675
+ * }
676
+ *
677
+ * const VirusSchema = new Schema({
678
+ * name: { type: String, required: true, set: inspector },
679
+ * taxonomy: { type: String, set: inspector }
680
+ * })
681
+ *
682
+ * const Virus = db.model('Virus', VirusSchema);
683
+ * const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
684
+ *
685
+ * console.log(v.name); // name is required
686
+ * console.log(v.taxonomy); // Parvovirinae
687
+ *
688
+ * You can also use setters to modify other properties on the document. If
689
+ * you're setting a property `name` on a document, the setter will run with
690
+ * `this` as the document. Be careful, in mongoose 5 setters will also run
691
+ * when querying by `name` with `this` as the query.
692
+ *
693
+ * const nameSchema = new Schema({ name: String, keywords: [String] });
694
+ * nameSchema.path('name').set(function(v) {
695
+ * // Need to check if `this` is a document, because in mongoose 5
696
+ * // setters will also run on queries, in which case `this` will be a
697
+ * // mongoose query object.
698
+ * if (this instanceof Document && v != null) {
699
+ * this.keywords = v.split(' ');
700
+ * }
701
+ * return v;
702
+ * });
703
+ *
704
+ * @param {Function} fn
705
+ * @return {SchemaType} this
706
+ * @api public
707
+ */
708
+
709
+ SchemaType.prototype.set = function(fn) {
710
+ if (typeof fn !== 'function') {
711
+ throw new TypeError('A setter must be a function.');
712
+ }
713
+ this.setters.push(fn);
714
+ return this;
715
+ };
716
+
717
+ /**
718
+ * Adds a getter to this schematype.
719
+ *
720
+ * #### Example:
721
+ *
722
+ * function dob (val) {
723
+ * if (!val) return val;
724
+ * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
725
+ * }
726
+ *
727
+ * // defining within the schema
728
+ * const s = new Schema({ born: { type: Date, get: dob })
729
+ *
730
+ * // or by retreiving its SchemaType
731
+ * const s = new Schema({ born: Date })
732
+ * s.path('born').get(dob)
733
+ *
734
+ * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.
735
+ *
736
+ * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:
737
+ *
738
+ * function obfuscate (cc) {
739
+ * return '****-****-****-' + cc.slice(cc.length-4, cc.length);
740
+ * }
741
+ *
742
+ * const AccountSchema = new Schema({
743
+ * creditCardNumber: { type: String, get: obfuscate }
744
+ * });
745
+ *
746
+ * const Account = db.model('Account', AccountSchema);
747
+ *
748
+ * Account.findById(id, function (err, found) {
749
+ * console.log(found.creditCardNumber); // '****-****-****-1234'
750
+ * });
751
+ *
752
+ * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.
753
+ *
754
+ * function inspector (val, priorValue, schematype) {
755
+ * if (schematype.options.required) {
756
+ * return schematype.path + ' is required';
757
+ * } else {
758
+ * return schematype.path + ' is not';
759
+ * }
760
+ * }
761
+ *
762
+ * const VirusSchema = new Schema({
763
+ * name: { type: String, required: true, get: inspector },
764
+ * taxonomy: { type: String, get: inspector }
765
+ * })
766
+ *
767
+ * const Virus = db.model('Virus', VirusSchema);
768
+ *
769
+ * Virus.findById(id, function (err, virus) {
770
+ * console.log(virus.name); // name is required
771
+ * console.log(virus.taxonomy); // taxonomy is not
772
+ * })
773
+ *
774
+ * @param {Function} fn
775
+ * @return {SchemaType} this
776
+ * @api public
777
+ */
778
+
779
+ SchemaType.prototype.get = function(fn) {
780
+ if (typeof fn !== 'function') {
781
+ throw new TypeError('A getter must be a function.');
782
+ }
783
+ this.getters.push(fn);
784
+ return this;
785
+ };
786
+
787
+ /**
788
+ * Adds validator(s) for this document path.
789
+ *
790
+ * Validators always receive the value to validate as their first argument and
791
+ * must return `Boolean`. Returning `false` or throwing an error means
792
+ * validation failed.
793
+ *
794
+ * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used.
795
+ *
796
+ * #### Example:
797
+ *
798
+ * // make sure every value is equal to "something"
799
+ * function validator (val) {
800
+ * return val === 'something';
801
+ * }
802
+ * new Schema({ name: { type: String, validate: validator }});
803
+ *
804
+ * // with a custom error message
805
+ *
806
+ * const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
807
+ * new Schema({ name: { type: String, validate: custom }});
808
+ *
809
+ * // adding many validators at a time
810
+ *
811
+ * const many = [
812
+ * { validator: validator, msg: 'uh oh' }
813
+ * , { validator: anotherValidator, msg: 'failed' }
814
+ * ]
815
+ * new Schema({ name: { type: String, validate: many }});
816
+ *
817
+ * // or utilizing SchemaType methods directly:
818
+ *
819
+ * const schema = new Schema({ name: 'string' });
820
+ * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');
821
+ *
822
+ * #### Error message templates:
823
+ *
824
+ * From the examples above, you may have noticed that error messages support
825
+ * basic templating. There are a few other template keywords besides `{PATH}`
826
+ * and `{VALUE}` too. To find out more, details are available
827
+ * [here](#error_messages_MongooseError-messages).
828
+ *
829
+ * If Mongoose's built-in error message templating isn't enough, Mongoose
830
+ * supports setting the `message` property to a function.
831
+ *
832
+ * schema.path('name').validate({
833
+ * validator: function(v) { return v.length > 5; },
834
+ * // `errors['name']` will be "name must have length 5, got 'foo'"
835
+ * message: function(props) {
836
+ * return `${props.path} must have length 5, got '${props.value}'`;
837
+ * }
838
+ * });
839
+ *
840
+ * To bypass Mongoose's error messages and just copy the error message that
841
+ * the validator throws, do this:
842
+ *
843
+ * schema.path('name').validate({
844
+ * validator: function() { throw new Error('Oops!'); },
845
+ * // `errors['name']` will be "Oops!"
846
+ * message: function(props) { return props.reason.message; }
847
+ * });
848
+ *
849
+ * #### Asynchronous validation:
850
+ *
851
+ * Mongoose supports validators that return a promise. A validator that returns
852
+ * a promise is called an _async validator_. Async validators run in
853
+ * parallel, and `validate()` will wait until all async validators have settled.
854
+ *
855
+ * schema.path('name').validate({
856
+ * validator: function (value) {
857
+ * return new Promise(function (resolve, reject) {
858
+ * resolve(false); // validation failed
859
+ * });
860
+ * }
861
+ * });
862
+ *
863
+ * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.
864
+ *
865
+ * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate).
866
+ *
867
+ * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along.
868
+ *
869
+ * const conn = mongoose.createConnection(..);
870
+ * conn.on('error', handleError);
871
+ *
872
+ * const Product = conn.model('Product', yourSchema);
873
+ * const dvd = new Product(..);
874
+ * dvd.save(); // emits error on the `conn` above
875
+ *
876
+ * If you want to handle these errors at the Model level, add an `error`
877
+ * listener to your Model as shown below.
878
+ *
879
+ * // registering an error listener on the Model lets us handle errors more locally
880
+ * Product.on('error', handleError);
881
+ *
882
+ * @param {RegExp|Function|Object} obj validator function, or hash describing options
883
+ * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails.
884
+ * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string
885
+ * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators.
886
+ * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string
887
+ * @param {String} [type] optional validator type
888
+ * @return {SchemaType} this
889
+ * @api public
890
+ */
891
+
892
+ SchemaType.prototype.validate = function(obj, message, type) {
893
+ if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') {
894
+ let properties;
895
+ if (typeof message === 'function') {
896
+ properties = { validator: obj, message: message };
897
+ properties.type = type || 'user defined';
898
+ } else if (message instanceof Object && !type) {
899
+ properties = isSimpleValidator(message) ? Object.assign({}, message) : utils.clone(message);
900
+ if (!properties.message) {
901
+ properties.message = properties.msg;
902
+ }
903
+ properties.validator = obj;
904
+ properties.type = properties.type || 'user defined';
905
+ } else {
906
+ if (message == null) {
907
+ message = MongooseError.messages.general.default;
908
+ }
909
+ if (!type) {
910
+ type = 'user defined';
911
+ }
912
+ properties = { message: message, type: type, validator: obj };
913
+ }
914
+
915
+ this.validators.push(properties);
916
+ return this;
917
+ }
918
+
919
+ let i;
920
+ let length;
921
+ let arg;
922
+
923
+ for (i = 0, length = arguments.length; i < length; i++) {
924
+ arg = arguments[i];
925
+ if (!utils.isPOJO(arg)) {
926
+ const msg = 'Invalid validator. Received (' + typeof arg + ') '
927
+ + arg
928
+ + '. See https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-validate';
929
+
930
+ throw new Error(msg);
931
+ }
932
+ this.validate(arg.validator, arg);
933
+ }
934
+
935
+ return this;
936
+ };
937
+
938
+ /**
939
+ * Adds a required validator to this SchemaType. The validator gets added
940
+ * to the front of this SchemaType's validators array using `unshift()`.
941
+ *
942
+ * #### Example:
943
+ *
944
+ * const s = new Schema({ born: { type: Date, required: true })
945
+ *
946
+ * // or with custom error message
947
+ *
948
+ * const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
949
+ *
950
+ * // or with a function
951
+ *
952
+ * const s = new Schema({
953
+ * userId: ObjectId,
954
+ * username: {
955
+ * type: String,
956
+ * required: function() { return this.userId != null; }
957
+ * }
958
+ * })
959
+ *
960
+ * // or with a function and a custom message
961
+ * const s = new Schema({
962
+ * userId: ObjectId,
963
+ * username: {
964
+ * type: String,
965
+ * required: [
966
+ * function() { return this.userId != null; },
967
+ * 'username is required if id is specified'
968
+ * ]
969
+ * }
970
+ * })
971
+ *
972
+ * // or through the path API
973
+ *
974
+ * s.path('name').required(true);
975
+ *
976
+ * // with custom error messaging
977
+ *
978
+ * s.path('name').required(true, 'grrr :( ');
979
+ *
980
+ * // or make a path conditionally required based on a function
981
+ * const isOver18 = function() { return this.age >= 18; };
982
+ * s.path('voterRegistrationId').required(isOver18);
983
+ *
984
+ * The required validator uses the SchemaType's `checkRequired` function to
985
+ * determine whether a given value satisfies the required validator. By default,
986
+ * a value satisfies the required validator if `val != null` (that is, if
987
+ * the value is not null nor undefined). However, most built-in mongoose schema
988
+ * types override the default `checkRequired` function:
989
+ *
990
+ * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object
991
+ * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean
992
+ * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.
993
+ * @param {String} [message] optional custom error message
994
+ * @return {SchemaType} this
995
+ * @see Customized Error Messages #error_messages_MongooseError-messages
996
+ * @see SchemaArray#checkRequired #schema_array_SchemaArray-checkRequired
997
+ * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired
998
+ * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer-schemaName
999
+ * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min
1000
+ * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto
1001
+ * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired
1002
+ * @api public
1003
+ */
1004
+
1005
+ SchemaType.prototype.required = function(required, message) {
1006
+ let customOptions = {};
1007
+
1008
+ if (arguments.length > 0 && required == null) {
1009
+ this.validators = this.validators.filter(function(v) {
1010
+ return v.validator !== this.requiredValidator;
1011
+ }, this);
1012
+
1013
+ this.isRequired = false;
1014
+ delete this.originalRequiredValue;
1015
+ return this;
1016
+ }
1017
+
1018
+ if (typeof required === 'object') {
1019
+ customOptions = required;
1020
+ message = customOptions.message || message;
1021
+ required = required.isRequired;
1022
+ }
1023
+
1024
+ if (required === false) {
1025
+ this.validators = this.validators.filter(function(v) {
1026
+ return v.validator !== this.requiredValidator;
1027
+ }, this);
1028
+
1029
+ this.isRequired = false;
1030
+ delete this.originalRequiredValue;
1031
+ return this;
1032
+ }
1033
+
1034
+ const _this = this;
1035
+ this.isRequired = true;
1036
+
1037
+ this.requiredValidator = function(v) {
1038
+ const cachedRequired = this && this.$__ && this.$__.cachedRequired;
1039
+
1040
+ // no validation when this path wasn't selected in the query.
1041
+ if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) {
1042
+ return true;
1043
+ }
1044
+
1045
+ // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we
1046
+ // don't call required functions multiple times in one validate call
1047
+ // See gh-6801
1048
+ if (cachedRequired != null && _this.path in cachedRequired) {
1049
+ const res = cachedRequired[_this.path] ?
1050
+ _this.checkRequired(v, this) :
1051
+ true;
1052
+ delete cachedRequired[_this.path];
1053
+ return res;
1054
+ } else if (typeof required === 'function') {
1055
+ return required.apply(this) ? _this.checkRequired(v, this) : true;
1056
+ }
1057
+
1058
+ return _this.checkRequired(v, this);
1059
+ };
1060
+ this.originalRequiredValue = required;
1061
+
1062
+ if (typeof required === 'string') {
1063
+ message = required;
1064
+ required = undefined;
1065
+ }
1066
+
1067
+ const msg = message || MongooseError.messages.general.required;
1068
+ this.validators.unshift(Object.assign({}, customOptions, {
1069
+ validator: this.requiredValidator,
1070
+ message: msg,
1071
+ type: 'required'
1072
+ }));
1073
+
1074
+ return this;
1075
+ };
1076
+
1077
+ /**
1078
+ * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
1079
+ * looks at to determine the foreign collection it should query.
1080
+ *
1081
+ * #### Example:
1082
+ *
1083
+ * const userSchema = new Schema({ name: String });
1084
+ * const User = mongoose.model('User', userSchema);
1085
+ *
1086
+ * const postSchema = new Schema({ user: mongoose.ObjectId });
1087
+ * postSchema.path('user').ref('User'); // Can set ref to a model name
1088
+ * postSchema.path('user').ref(User); // Or a model class
1089
+ * postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name
1090
+ * postSchema.path('user').ref(() => User); // Or a function that returns the model class
1091
+ *
1092
+ * // Or you can just declare the `ref` inline in your schema
1093
+ * const postSchema2 = new Schema({
1094
+ * user: { type: mongoose.ObjectId, ref: User }
1095
+ * });
1096
+ *
1097
+ * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model.
1098
+ * @return {SchemaType} this
1099
+ * @api public
1100
+ */
1101
+
1102
+ SchemaType.prototype.ref = function(ref) {
1103
+ this.options.ref = ref;
1104
+ return this;
1105
+ };
1106
+
1107
+ /**
1108
+ * Gets the default value
1109
+ *
1110
+ * @param {Object} scope the scope which callback are executed
1111
+ * @param {Boolean} init
1112
+ * @return {Any} The Stored default value.
1113
+ * @api private
1114
+ */
1115
+
1116
+ SchemaType.prototype.getDefault = function(scope, init, options) {
1117
+ let ret;
1118
+ if (typeof this.defaultValue === 'function') {
1119
+ if (
1120
+ this.defaultValue === Date.now ||
1121
+ this.defaultValue === Array ||
1122
+ this.defaultValue.name.toLowerCase() === 'objectid'
1123
+ ) {
1124
+ ret = this.defaultValue.call(scope);
1125
+ } else {
1126
+ ret = this.defaultValue.call(scope, scope);
1127
+ }
1128
+ } else {
1129
+ ret = this.defaultValue;
1130
+ }
1131
+
1132
+ if (ret !== null && ret !== undefined) {
1133
+ if (typeof ret === 'object' && (!this.options || !this.options.shared)) {
1134
+ ret = utils.clone(ret);
1135
+ }
1136
+
1137
+ if (options && options.skipCast) {
1138
+ return this._applySetters(ret, scope);
1139
+ }
1140
+
1141
+ const casted = this.applySetters(ret, scope, init, undefined, setOptionsForDefaults);
1142
+ if (casted && !Array.isArray(casted) && casted.$isSingleNested) {
1143
+ casted.$__parent = scope;
1144
+ }
1145
+ return casted;
1146
+ }
1147
+ return ret;
1148
+ };
1149
+
1150
+ /**
1151
+ * Applies setters without casting
1152
+ *
1153
+ * @param {Any} value
1154
+ * @param {Any} scope
1155
+ * @param {Boolean} init
1156
+ * @param {Any} priorVal
1157
+ * @param {Object} [options]
1158
+ * @instance
1159
+ * @api private
1160
+ */
1161
+
1162
+ SchemaType.prototype._applySetters = function(value, scope, init, priorVal, options) {
1163
+ let v = value;
1164
+ if (init) {
1165
+ return v;
1166
+ }
1167
+ const setters = this.setters;
1168
+
1169
+ for (let i = setters.length - 1; i >= 0; i--) {
1170
+ v = setters[i].call(scope, v, priorVal, this, options);
1171
+ }
1172
+
1173
+ return v;
1174
+ };
1175
+
1176
+ /*!
1177
+ * ignore
1178
+ */
1179
+
1180
+ SchemaType.prototype._castNullish = function _castNullish(v) {
1181
+ return v;
1182
+ };
1183
+
1184
+ /**
1185
+ * Applies setters
1186
+ *
1187
+ * @param {Object} value
1188
+ * @param {Object} scope
1189
+ * @param {Boolean} init
1190
+ * @return {Any}
1191
+ * @api private
1192
+ */
1193
+
1194
+ SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) {
1195
+ let v = this._applySetters(value, scope, init, priorVal, options);
1196
+ if (v == null) {
1197
+ return this._castNullish(v);
1198
+ }
1199
+
1200
+ // do not cast until all setters are applied #665
1201
+ v = this.cast(v, scope, init, priorVal, options);
1202
+
1203
+ return v;
1204
+ };
1205
+
1206
+ /**
1207
+ * Applies getters to a value
1208
+ *
1209
+ * @param {Object} value
1210
+ * @param {Object} scope
1211
+ * @return {Any}
1212
+ * @api private
1213
+ */
1214
+
1215
+ SchemaType.prototype.applyGetters = function(value, scope) {
1216
+ let v = value;
1217
+ const getters = this.getters;
1218
+ const len = getters.length;
1219
+
1220
+ if (len === 0) {
1221
+ return v;
1222
+ }
1223
+
1224
+ for (let i = 0; i < len; ++i) {
1225
+ v = getters[i].call(scope, v, this);
1226
+ }
1227
+
1228
+ return v;
1229
+ };
1230
+
1231
+ /**
1232
+ * Sets default `select()` behavior for this path.
1233
+ *
1234
+ * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level.
1235
+ *
1236
+ * #### Example:
1237
+ *
1238
+ * T = db.model('T', new Schema({ x: { type: String, select: true }}));
1239
+ * T.find(..); // field x will always be selected ..
1240
+ * // .. unless overridden;
1241
+ * T.find().select('-x').exec(callback);
1242
+ *
1243
+ * @param {Boolean} val
1244
+ * @return {SchemaType} this
1245
+ * @api public
1246
+ */
1247
+
1248
+ SchemaType.prototype.select = function select(val) {
1249
+ this.selected = !!val;
1250
+ return this;
1251
+ };
1252
+
1253
+ /**
1254
+ * Performs a validation of `value` using the validators declared for this SchemaType.
1255
+ *
1256
+ * @param {Any} value
1257
+ * @param {Function} callback
1258
+ * @param {Object} scope
1259
+ * @param {Object} [options]
1260
+ * @param {String} [options.path]
1261
+ * @return {Any} If no validators, returns the output from calling `fn`, otherwise no return
1262
+ * @api public
1263
+ */
1264
+
1265
+ SchemaType.prototype.doValidate = function(value, fn, scope, options) {
1266
+ let err = false;
1267
+ const path = this.path;
1268
+
1269
+ // Avoid non-object `validators`
1270
+ const validators = this.validators.
1271
+ filter(v => typeof v === 'object' && v !== null);
1272
+
1273
+ let count = validators.length;
1274
+
1275
+ if (!count) {
1276
+ return fn(null);
1277
+ }
1278
+
1279
+ for (let i = 0, len = validators.length; i < len; ++i) {
1280
+ if (err) {
1281
+ break;
1282
+ }
1283
+
1284
+ const v = validators[i];
1285
+ const validator = v.validator;
1286
+ let ok;
1287
+
1288
+ const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : utils.clone(v);
1289
+ validatorProperties.path = options && options.path ? options.path : path;
1290
+ validatorProperties.fullPath = this.$fullPath;
1291
+ validatorProperties.value = value;
1292
+
1293
+ if (validator instanceof RegExp) {
1294
+ validate(validator.test(value), validatorProperties, scope);
1295
+ continue;
1296
+ }
1297
+
1298
+ if (typeof validator !== 'function') {
1299
+ continue;
1300
+ }
1301
+
1302
+ if (value === undefined && validator !== this.requiredValidator) {
1303
+ validate(true, validatorProperties, scope);
1304
+ continue;
1305
+ }
1306
+
1307
+ try {
1308
+ if (validatorProperties.propsParameter) {
1309
+ ok = validator.call(scope, value, validatorProperties);
1310
+ } else {
1311
+ ok = validator.call(scope, value);
1312
+ }
1313
+ } catch (error) {
1314
+ ok = false;
1315
+ validatorProperties.reason = error;
1316
+ if (error.message) {
1317
+ validatorProperties.message = error.message;
1318
+ }
1319
+ }
1320
+
1321
+ if (ok != null && typeof ok.then === 'function') {
1322
+ ok.then(
1323
+ function(ok) { validate(ok, validatorProperties, scope); },
1324
+ function(error) {
1325
+ validatorProperties.reason = error;
1326
+ validatorProperties.message = error.message;
1327
+ ok = false;
1328
+ validate(ok, validatorProperties, scope);
1329
+ });
1330
+ } else {
1331
+ validate(ok, validatorProperties, scope);
1332
+ }
1333
+ }
1334
+
1335
+ function validate(ok, validatorProperties, scope) {
1336
+ if (err) {
1337
+ return;
1338
+ }
1339
+ if (ok === undefined || ok) {
1340
+ if (--count <= 0) {
1341
+ immediate(function() {
1342
+ fn(null);
1343
+ });
1344
+ }
1345
+ } else {
1346
+ const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
1347
+ err = new ErrorConstructor(validatorProperties, scope);
1348
+ err[validatorErrorSymbol] = true;
1349
+ immediate(function() {
1350
+ fn(err);
1351
+ });
1352
+ }
1353
+ }
1354
+ };
1355
+
1356
+
1357
+ function _validate(ok, validatorProperties) {
1358
+ if (ok !== undefined && !ok) {
1359
+ const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
1360
+ const err = new ErrorConstructor(validatorProperties);
1361
+ err[validatorErrorSymbol] = true;
1362
+ return err;
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * Performs a validation of `value` using the validators declared for this SchemaType.
1368
+ *
1369
+ * #### Note:
1370
+ *
1371
+ * This method ignores the asynchronous validators.
1372
+ *
1373
+ * @param {Any} value
1374
+ * @param {Object} scope
1375
+ * @param {Object} [options]
1376
+ * @param {Object} [options.path]
1377
+ * @return {MongooseError|null}
1378
+ * @api private
1379
+ */
1380
+
1381
+ SchemaType.prototype.doValidateSync = function(value, scope, options) {
1382
+ const path = this.path;
1383
+ const count = this.validators.length;
1384
+
1385
+ if (!count) {
1386
+ return null;
1387
+ }
1388
+
1389
+ let validators = this.validators;
1390
+ if (value === void 0) {
1391
+ if (this.validators.length !== 0 && this.validators[0].type === 'required') {
1392
+ validators = [this.validators[0]];
1393
+ } else {
1394
+ return null;
1395
+ }
1396
+ }
1397
+
1398
+ let err = null;
1399
+ let i = 0;
1400
+ const len = validators.length;
1401
+ for (i = 0; i < len; ++i) {
1402
+
1403
+ const v = validators[i];
1404
+
1405
+ if (v === null || typeof v !== 'object') {
1406
+ continue;
1407
+ }
1408
+
1409
+ const validator = v.validator;
1410
+ const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : utils.clone(v);
1411
+ validatorProperties.path = options && options.path ? options.path : path;
1412
+ validatorProperties.fullPath = this.$fullPath;
1413
+ validatorProperties.value = value;
1414
+ let ok = false;
1415
+
1416
+ // Skip any explicit async validators. Validators that return a promise
1417
+ // will still run, but won't trigger any errors.
1418
+ if (isAsyncFunction(validator)) {
1419
+ continue;
1420
+ }
1421
+
1422
+ if (validator instanceof RegExp) {
1423
+ err = _validate(validator.test(value), validatorProperties);
1424
+ continue;
1425
+ }
1426
+
1427
+ if (typeof validator !== 'function') {
1428
+ continue;
1429
+ }
1430
+
1431
+ try {
1432
+ if (validatorProperties.propsParameter) {
1433
+ ok = validator.call(scope, value, validatorProperties);
1434
+ } else {
1435
+ ok = validator.call(scope, value);
1436
+ }
1437
+ } catch (error) {
1438
+ ok = false;
1439
+ validatorProperties.reason = error;
1440
+ }
1441
+
1442
+ // Skip any validators that return a promise, we can't handle those
1443
+ // synchronously
1444
+ if (ok != null && typeof ok.then === 'function') {
1445
+ continue;
1446
+ }
1447
+ err = _validate(ok, validatorProperties);
1448
+ if (err) {
1449
+ break;
1450
+ }
1451
+ }
1452
+
1453
+ return err;
1454
+ };
1455
+
1456
+ /**
1457
+ * Determines if value is a valid Reference.
1458
+ *
1459
+ * @param {SchemaType} self
1460
+ * @param {Object} value
1461
+ * @param {Document} doc
1462
+ * @param {Boolean} init
1463
+ * @return {Boolean}
1464
+ * @api private
1465
+ */
1466
+
1467
+ SchemaType._isRef = function(self, value, doc, init) {
1468
+ // fast path
1469
+ let ref = init && self.options && (self.options.ref || self.options.refPath);
1470
+
1471
+ if (!ref && doc && doc.$__ != null) {
1472
+ // checks for
1473
+ // - this populated with adhoc model and no ref was set in schema OR
1474
+ // - setting / pushing values after population
1475
+ const path = doc.$__fullPath(self.path, true);
1476
+
1477
+ const owner = doc.ownerDocument();
1478
+ ref = (path != null && owner.$populated(path)) || doc.$populated(self.path);
1479
+ }
1480
+
1481
+ if (ref) {
1482
+ if (value == null) {
1483
+ return true;
1484
+ }
1485
+ if (!Buffer.isBuffer(value) && // buffers are objects too
1486
+ value._bsontype !== 'Binary' // raw binary value from the db
1487
+ && utils.isObject(value) // might have deselected _id in population query
1488
+ ) {
1489
+ return true;
1490
+ }
1491
+
1492
+ return init;
1493
+ }
1494
+
1495
+ return false;
1496
+ };
1497
+
1498
+ /*!
1499
+ * ignore
1500
+ */
1501
+
1502
+ SchemaType.prototype._castRef = function _castRef(value, doc, init) {
1503
+ if (value == null) {
1504
+ return value;
1505
+ }
1506
+
1507
+ if (value.$__ != null) {
1508
+ value.$__.wasPopulated = value.$__.wasPopulated || { value: value._id };
1509
+ return value;
1510
+ }
1511
+
1512
+ // setting a populated path
1513
+ if (Buffer.isBuffer(value) || !utils.isObject(value)) {
1514
+ if (init) {
1515
+ return value;
1516
+ }
1517
+ throw new CastError(this.instance, value, this.path, null, this);
1518
+ }
1519
+
1520
+ // Handle the case where user directly sets a populated
1521
+ // path to a plain object; cast to the Model used in
1522
+ // the population query.
1523
+ const path = doc.$__fullPath(this.path, true);
1524
+ const owner = doc.ownerDocument();
1525
+ const pop = owner.$populated(path, true);
1526
+
1527
+ let ret = value;
1528
+ if (!doc.$__.populated ||
1529
+ !doc.$__.populated[path] ||
1530
+ !doc.$__.populated[path].options ||
1531
+ !doc.$__.populated[path].options.options ||
1532
+ !doc.$__.populated[path].options.options.lean) {
1533
+ ret = new pop.options[populateModelSymbol](value);
1534
+ ret.$__.wasPopulated = { value: ret._id };
1535
+ }
1536
+
1537
+ return ret;
1538
+ };
1539
+
1540
+ /*!
1541
+ * ignore
1542
+ */
1543
+
1544
+ function handleSingle(val) {
1545
+ return this.castForQuery(val);
1546
+ }
1547
+
1548
+ /*!
1549
+ * ignore
1550
+ */
1551
+
1552
+ function handleArray(val) {
1553
+ const _this = this;
1554
+ if (!Array.isArray(val)) {
1555
+ return [this.castForQuery(val)];
1556
+ }
1557
+ return val.map(function(m) {
1558
+ return _this.castForQuery(m);
1559
+ });
1560
+ }
1561
+
1562
+ /**
1563
+ * Just like handleArray, except also allows `[]` because surprisingly
1564
+ * `$in: [1, []]` works fine
1565
+ * @api private
1566
+ */
1567
+
1568
+ function handle$in(val) {
1569
+ const _this = this;
1570
+ if (!Array.isArray(val)) {
1571
+ return [this.castForQuery(val)];
1572
+ }
1573
+ return val.map(function(m) {
1574
+ if (Array.isArray(m) && m.length === 0) {
1575
+ return m;
1576
+ }
1577
+ return _this.castForQuery(m);
1578
+ });
1579
+ }
1580
+
1581
+ /*!
1582
+ * ignore
1583
+ */
1584
+
1585
+ SchemaType.prototype.$conditionalHandlers = {
1586
+ $all: handleArray,
1587
+ $eq: handleSingle,
1588
+ $in: handle$in,
1589
+ $ne: handleSingle,
1590
+ $nin: handle$in,
1591
+ $exists: $exists,
1592
+ $type: $type
1593
+ };
1594
+
1595
+ /**
1596
+ * Wraps `castForQuery` to handle context
1597
+ * @param {Object} params
1598
+ * @instance
1599
+ * @api private
1600
+ */
1601
+
1602
+ SchemaType.prototype.castForQueryWrapper = function(params) {
1603
+ this.$$context = params.context;
1604
+ if ('$conditional' in params) {
1605
+ const ret = this.castForQuery(params.$conditional, params.val);
1606
+ this.$$context = null;
1607
+ return ret;
1608
+ }
1609
+ if (params.$skipQueryCastForUpdate || params.$applySetters) {
1610
+ const ret = this._castForQuery(params.val);
1611
+ this.$$context = null;
1612
+ return ret;
1613
+ }
1614
+
1615
+ const ret = this.castForQuery(params.val);
1616
+ this.$$context = null;
1617
+ return ret;
1618
+ };
1619
+
1620
+ /**
1621
+ * Cast the given value with the given optional query operator.
1622
+ *
1623
+ * @param {String} [$conditional] query operator, like `$eq` or `$in`
1624
+ * @param {Any} val
1625
+ * @return {Any}
1626
+ * @api private
1627
+ */
1628
+
1629
+ SchemaType.prototype.castForQuery = function($conditional, val) {
1630
+ let handler;
1631
+ if (arguments.length === 2) {
1632
+ handler = this.$conditionalHandlers[$conditional];
1633
+ if (!handler) {
1634
+ throw new Error('Can\'t use ' + $conditional);
1635
+ }
1636
+ return handler.call(this, val);
1637
+ }
1638
+ val = $conditional;
1639
+ return this._castForQuery(val);
1640
+ };
1641
+
1642
+ /**
1643
+ * Internal switch for runSetters
1644
+ *
1645
+ * @param {Any} val
1646
+ * @return {Any}
1647
+ * @api private
1648
+ */
1649
+
1650
+ SchemaType.prototype._castForQuery = function(val) {
1651
+ return this.applySetters(val, this.$$context);
1652
+ };
1653
+
1654
+ /**
1655
+ * Set & Get the `checkRequired` function
1656
+ * Override the function the required validator uses to check whether a value
1657
+ * passes the `required` check. Override this on the individual SchemaType.
1658
+ *
1659
+ * #### Example:
1660
+ *
1661
+ * // Use this to allow empty strings to pass the `required` validator
1662
+ * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
1663
+ *
1664
+ * @param {Function} [fn] If set, will overwrite the current set function
1665
+ * @return {Function} The input `fn` or the already set function
1666
+ * @static
1667
+ * @memberOf SchemaType
1668
+ * @function checkRequired
1669
+ * @api public
1670
+ */
1671
+
1672
+ SchemaType.checkRequired = function(fn) {
1673
+ if (arguments.length !== 0) {
1674
+ this._checkRequired = fn;
1675
+ }
1676
+
1677
+ return this._checkRequired;
1678
+ };
1679
+
1680
+ /**
1681
+ * Default check for if this path satisfies the `required` validator.
1682
+ *
1683
+ * @param {Any} val
1684
+ * @return {Boolean} `true` when the value is not `null`, `false` otherwise
1685
+ * @api private
1686
+ */
1687
+
1688
+ SchemaType.prototype.checkRequired = function(val) {
1689
+ return val != null;
1690
+ };
1691
+
1692
+ /**
1693
+ * Clone the current SchemaType
1694
+ *
1695
+ * @return {SchemaType} The cloned SchemaType instance
1696
+ * @api private
1697
+ */
1698
+
1699
+ SchemaType.prototype.clone = function() {
1700
+ const options = Object.assign({}, this.options);
1701
+ const schematype = new this.constructor(this.path, options, this.instance);
1702
+ schematype.validators = this.validators.slice();
1703
+ if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator;
1704
+ if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue;
1705
+ if (this.$immutable !== undefined && this.options.immutable === undefined) {
1706
+ schematype.$immutable = this.$immutable;
1707
+
1708
+ handleImmutable(schematype);
1709
+ }
1710
+ if (this._index !== undefined) schematype._index = this._index;
1711
+ if (this.selected !== undefined) schematype.selected = this.selected;
1712
+ if (this.isRequired !== undefined) schematype.isRequired = this.isRequired;
1713
+ if (this.originalRequiredValue !== undefined) schematype.originalRequiredValue = this.originalRequiredValue;
1714
+ schematype.getters = this.getters.slice();
1715
+ schematype.setters = this.setters.slice();
1716
+ return schematype;
1717
+ };
1718
+
1719
+ /*!
1720
+ * Module exports.
1721
+ */
1722
+
1723
+ module.exports = exports = SchemaType;
1724
+
1725
+ exports.CastError = CastError;
1726
+
1727
+ exports.ValidatorError = ValidatorError;