@datanimbus/mongoose 6.13.13 → 9.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -70
- package/eslint.config.mjs +202 -0
- package/index.js +2 -1
- package/lib/aggregate.js +276 -174
- package/lib/cast/bigint.js +46 -0
- package/lib/cast/boolean.js +3 -3
- package/lib/cast/decimal128.js +4 -1
- package/lib/cast/double.js +56 -0
- package/lib/cast/int32.js +42 -0
- package/lib/cast/number.js +6 -6
- package/lib/cast/objectid.js +3 -3
- package/lib/cast/string.js +3 -3
- package/lib/cast/uuid.js +35 -0
- package/lib/cast.js +100 -92
- package/lib/collection.js +31 -22
- package/lib/connection.js +792 -507
- package/lib/constants.js +73 -0
- package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
- package/lib/cursor/changeStream.js +218 -0
- package/lib/cursor/queryCursor.js +676 -0
- package/lib/defaults/schemaDefaultsCache.js +62 -0
- package/lib/document.js +2419 -1306
- package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
- package/lib/drivers/node-mongodb-native/collection.js +101 -135
- package/lib/drivers/node-mongodb-native/connection.js +386 -28
- package/lib/drivers/node-mongodb-native/index.js +3 -5
- package/lib/error/browserMissingSchema.js +5 -4
- package/lib/error/bulkSaveIncompleteError.js +44 -0
- package/lib/error/cast.js +30 -21
- package/lib/error/createCollectionsError.js +26 -0
- package/lib/error/divergentArray.js +11 -9
- package/lib/error/eachAsyncMultiError.js +2 -2
- package/lib/error/index.js +38 -29
- package/lib/error/invalidSchemaOption.js +32 -0
- package/lib/error/messages.js +4 -3
- package/lib/error/missingSchema.js +8 -6
- package/lib/error/notFound.js +7 -5
- package/lib/error/objectExpected.js +9 -8
- package/lib/error/objectParameter.js +12 -11
- package/lib/error/overwriteModel.js +7 -6
- package/lib/error/parallelSave.js +11 -8
- package/lib/error/parallelValidate.js +9 -7
- package/lib/error/serverSelection.js +1 -0
- package/lib/error/setOptionError.js +11 -9
- package/lib/error/strict.js +12 -10
- package/lib/error/strictPopulate.js +11 -9
- package/lib/error/syncIndexes.js +2 -2
- package/lib/error/validation.js +11 -17
- package/lib/error/validator.js +9 -8
- package/lib/error/version.js +12 -10
- package/lib/filters/operators.js +8 -0
- package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
- package/lib/helpers/buildMiddlewareFilter.js +42 -0
- package/lib/helpers/clone.js +121 -35
- package/lib/helpers/common.js +7 -7
- package/lib/helpers/cursor/eachAsync.js +14 -11
- package/lib/helpers/cursor/waitForInitialization.js +17 -0
- package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
- package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
- package/lib/helpers/discriminator/getConstructor.js +9 -6
- package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
- package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
- package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
- package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
- package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
- package/lib/helpers/document/applyDefaults.js +82 -14
- package/lib/helpers/document/applyTimestamps.js +106 -0
- package/lib/helpers/document/applyVirtuals.js +147 -0
- package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
- package/lib/helpers/document/compile.js +20 -15
- package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
- package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
- package/lib/helpers/document/handleSpreadDoc.js +2 -1
- package/lib/helpers/document/isInPathsToSave.js +24 -0
- package/lib/helpers/document/toObjectRecursive.js +49 -0
- package/lib/helpers/get.js +1 -1
- package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
- package/lib/helpers/getInheritedProperty.js +28 -0
- package/lib/helpers/getOwnProperty.js +19 -0
- package/lib/helpers/indexes/applySchemaCollation.js +1 -1
- package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
- package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
- package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
- package/lib/helpers/indexes/isIndexEqual.js +13 -12
- package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
- package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
- package/lib/helpers/isBsonType.js +3 -6
- package/lib/helpers/isMongooseDocument.js +24 -0
- package/lib/helpers/isMongooseObject.js +6 -4
- package/lib/helpers/isObject.js +2 -2
- package/lib/helpers/isPOJO.js +12 -0
- package/lib/helpers/isSimpleValidator.js +2 -2
- package/lib/helpers/minimize.js +41 -0
- package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
- package/lib/helpers/model/applyHooks.js +72 -54
- package/lib/helpers/model/applyMethods.js +3 -3
- package/lib/helpers/model/applyStaticHooks.js +20 -50
- package/lib/helpers/model/castBulkWrite.js +278 -172
- package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
- package/lib/helpers/model/discriminator.js +77 -21
- package/lib/helpers/omitUndefined.js +20 -0
- package/lib/helpers/parallelLimit.js +61 -34
- package/lib/helpers/path/setDottedPath.js +1 -1
- package/lib/helpers/pathTrie.js +167 -0
- package/lib/helpers/pluralize.js +5 -4
- package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
- package/lib/helpers/populate/assignVals.js +46 -21
- package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
- package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
- package/lib/helpers/populate/getSchemaTypes.js +27 -30
- package/lib/helpers/populate/getVirtual.js +31 -0
- package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
- package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
- package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
- package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
- package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
- package/lib/helpers/populate/splitPopulateQuery.js +81 -0
- package/lib/helpers/printJestWarning.js +1 -1
- package/lib/helpers/processConnectionOptions.js +7 -2
- package/lib/helpers/projection/applyProjection.js +8 -2
- package/lib/helpers/projection/hasIncludedChildren.js +1 -1
- package/lib/helpers/projection/isExclusive.js +8 -6
- package/lib/helpers/projection/isInclusive.js +2 -1
- package/lib/helpers/projection/isPathExcluded.js +3 -3
- package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
- package/lib/helpers/projection/isSubpath.js +1 -1
- package/lib/helpers/projection/parseProjection.js +9 -4
- package/lib/helpers/query/applyGlobalOption.js +9 -9
- package/lib/helpers/query/cast$expr.js +52 -23
- package/lib/helpers/query/castFilterPath.js +22 -22
- package/lib/helpers/query/castUpdate.js +207 -79
- package/lib/helpers/query/cloneMongooseOptions.js +44 -0
- package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
- package/lib/helpers/query/handleImmutable.js +18 -2
- package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
- package/lib/helpers/query/sanitizeFilter.js +3 -2
- package/lib/helpers/query/selectPopulatedFields.js +13 -0
- package/lib/helpers/query/validOps.js +1 -22
- package/lib/helpers/schema/applyPlugins.js +2 -2
- package/lib/helpers/schema/applyReadConcern.js +20 -0
- package/lib/helpers/schema/applyWriteConcern.js +12 -3
- package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
- package/lib/helpers/schema/getIndexes.js +20 -13
- package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
- package/lib/helpers/schema/getPath.js +11 -3
- package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
- package/lib/helpers/schema/handleIdOption.js +1 -1
- package/lib/helpers/schema/idGetter.js +7 -2
- package/lib/helpers/schema/merge.js +9 -1
- package/lib/helpers/schematype/getConditionalHandler.js +23 -0
- package/lib/helpers/schematype/handleImmutable.js +1 -1
- package/lib/helpers/setDefaultsOnInsert.js +85 -43
- package/lib/helpers/symbols.js +4 -4
- package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
- package/lib/helpers/timestamps/setupTimestamps.js +69 -37
- package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
- package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
- package/lib/helpers/update/castArrayFilters.js +68 -29
- package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
- package/lib/helpers/update/modifiedPaths.js +2 -2
- package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
- package/lib/helpers/updateValidators.js +87 -128
- package/lib/index.js +6 -1320
- package/lib/internal.js +7 -1
- package/lib/model.js +2587 -2618
- package/lib/modifiedPathsSnapshot.js +9 -0
- package/lib/mongoose.js +1456 -0
- package/lib/options/saveOptions.js +2 -0
- package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
- package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
- package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
- package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
- package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
- package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
- package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
- package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
- package/lib/options/schemaSubdocumentOptions.js +89 -0
- package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
- package/lib/options/schemaUnionOptions.js +32 -0
- package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
- package/lib/options.js +4 -1
- package/lib/plugins/index.js +0 -2
- package/lib/plugins/saveSubdocs.js +85 -50
- package/lib/plugins/sharding.js +43 -15
- package/lib/plugins/trackTransaction.js +46 -34
- package/lib/query.js +1844 -1909
- package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
- package/lib/schema/array.js +229 -169
- package/lib/schema/bigint.js +281 -0
- package/lib/schema/boolean.js +90 -26
- package/lib/schema/buffer.js +119 -50
- package/lib/schema/date.js +102 -38
- package/lib/schema/decimal128.js +88 -37
- package/lib/schema/{documentarray.js → documentArray.js} +259 -151
- package/lib/schema/documentArrayElement.js +180 -0
- package/lib/schema/double.js +244 -0
- package/lib/schema/index.js +12 -19
- package/lib/schema/int32.js +288 -0
- package/lib/schema/map.js +129 -20
- package/lib/schema/mixed.js +40 -26
- package/lib/schema/number.js +128 -51
- package/lib/schema/{objectid.js → objectId.js} +89 -47
- package/lib/schema/operators/exists.js +1 -1
- package/lib/schema/operators/geospatial.js +2 -2
- package/lib/schema/operators/text.js +4 -4
- package/lib/schema/string.js +125 -66
- package/lib/schema/subdocument.js +443 -0
- package/lib/schema/symbols.js +2 -0
- package/lib/schema/union.js +167 -0
- package/lib/schema/uuid.js +90 -120
- package/lib/schema.js +1267 -388
- package/lib/{schematype.js → schemaType.js} +481 -246
- package/lib/standardSchema/convertErrorToIssues.js +20 -0
- package/lib/{statemachine.js → stateMachine.js} +66 -17
- package/lib/tracing.js +38 -0
- package/lib/types/array/index.js +13 -10
- package/lib/types/array/methods/index.js +243 -63
- package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
- package/lib/types/buffer.js +31 -14
- package/lib/types/decimal128.js +1 -1
- package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
- package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
- package/lib/types/double.js +13 -0
- package/lib/types/index.js +5 -2
- package/lib/types/map.js +62 -25
- package/lib/types/objectid.js +2 -2
- package/lib/types/subdocument.js +79 -58
- package/lib/types/uuid.js +13 -0
- package/lib/utils.js +201 -155
- package/lib/{validoptions.js → validOptions.js} +10 -2
- package/lib/{virtualtype.js → virtualType.js} +47 -18
- package/package.json +75 -92
- package/types/aggregate.d.ts +31 -7
- package/types/augmentations.d.ts +2 -2
- package/types/collection.d.ts +21 -16
- package/types/connection.d.ts +82 -27
- package/types/cursor.d.ts +15 -10
- package/types/document.d.ts +137 -56
- package/types/error.d.ts +11 -6
- package/types/expressions.d.ts +33 -2
- package/types/index.d.ts +805 -190
- package/types/indexes.d.ts +85 -13
- package/types/inferhydrateddoctype.d.ts +151 -0
- package/types/inferrawdoctype.d.ts +201 -0
- package/types/inferschematype.d.ts +287 -128
- package/types/middlewares.d.ts +50 -7
- package/types/models.d.ts +1555 -268
- package/types/mongooseoptions.d.ts +56 -7
- package/types/pipelinestage.d.ts +42 -3
- package/types/populate.d.ts +63 -1
- package/types/query.d.ts +592 -255
- package/types/schemaoptions.d.ts +78 -12
- package/types/schematypes.d.ts +254 -65
- package/types/session.d.ts +0 -4
- package/types/tracing.d.ts +10 -0
- package/types/types.d.ts +25 -8
- package/types/utility.d.ts +329 -30
- package/types/validation.d.ts +19 -14
- package/types/virtuals.d.ts +10 -10
- package/.eslintrc.js +0 -232
- package/.mocharc.yml +0 -4
- package/browser.js +0 -8
- package/lgtm.yml +0 -12
- package/lib/browser.js +0 -158
- package/lib/browserDocument.js +0 -101
- package/lib/cursor/ChangeStream.js +0 -154
- package/lib/cursor/QueryCursor.js +0 -545
- package/lib/document_provider.js +0 -30
- package/lib/drivers/browser/ReadPreference.js +0 -7
- package/lib/drivers/browser/binary.js +0 -14
- package/lib/drivers/browser/decimal128.js +0 -7
- package/lib/drivers/browser/index.js +0 -16
- package/lib/drivers/browser/objectid.js +0 -29
- package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
- package/lib/drivers/node-mongodb-native/binary.js +0 -10
- package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
- package/lib/drivers/node-mongodb-native/objectid.js +0 -16
- package/lib/error/disconnected.js +0 -33
- package/lib/helpers/printStrictQueryWarning.js +0 -11
- package/lib/helpers/promiseOrCallback.js +0 -55
- package/lib/helpers/query/applyQueryMiddleware.js +0 -79
- package/lib/helpers/query/completeMany.js +0 -52
- package/lib/helpers/query/wrapThunk.js +0 -36
- package/lib/options/SchemaSubdocumentOptions.js +0 -42
- package/lib/options/removeOptions.js +0 -14
- package/lib/plugins/removeSubdocs.js +0 -31
- package/lib/plugins/validateBeforeSave.js +0 -45
- package/lib/promise_provider.js +0 -49
- package/lib/schema/DocumentArrayElement.js +0 -100
- package/lib/schema/SubdocumentPath.js +0 -369
- package/scripts/build-browser.js +0 -18
- package/scripts/create-tarball.js +0 -7
- package/scripts/generateSearch.js +0 -154
- package/scripts/tsc-diagnostics-check.js +0 -15
- package/tools/auth.js +0 -31
- package/tools/repl.js +0 -35
- package/tools/sharded.js +0 -46
- package/tsconfig.json +0 -9
- /package/lib/{connectionstate.js → connectionState.js} +0 -0
- /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
- /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
- /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
|
@@ -5,13 +5,15 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
const MongooseError = require('./error/index');
|
|
8
|
-
const SchemaTypeOptions = require('./options/
|
|
8
|
+
const SchemaTypeOptions = require('./options/schemaTypeOptions');
|
|
9
9
|
const $exists = require('./schema/operators/exists');
|
|
10
10
|
const $type = require('./schema/operators/type');
|
|
11
|
+
const clone = require('./helpers/clone');
|
|
12
|
+
const getConditionalHandler = require('./helpers/schematype/getConditionalHandler');
|
|
11
13
|
const handleImmutable = require('./helpers/schematype/handleImmutable');
|
|
12
14
|
const isAsyncFunction = require('./helpers/isAsyncFunction');
|
|
15
|
+
const isMongooseDocument = require('./helpers/isMongooseDocument');
|
|
13
16
|
const isSimpleValidator = require('./helpers/isSimpleValidator');
|
|
14
|
-
const immediate = require('./helpers/immediate');
|
|
15
17
|
const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
|
|
16
18
|
const utils = require('./utils');
|
|
17
19
|
const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol;
|
|
@@ -33,21 +35,25 @@ const setOptionsForDefaults = { _skipMarkModified: true };
|
|
|
33
35
|
* const schema = new Schema({ name: String });
|
|
34
36
|
* schema.path('name') instanceof SchemaType; // true
|
|
35
37
|
*
|
|
36
|
-
* @param {
|
|
37
|
-
* @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html)
|
|
38
|
-
* @param {
|
|
38
|
+
* @param {string} path
|
|
39
|
+
* @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](https://mongoosejs.com/docs/api/schematypeoptions.html)
|
|
40
|
+
* @param {string} [instance]
|
|
41
|
+
* @param {Schema} [parentSchema]
|
|
39
42
|
* @api public
|
|
40
43
|
*/
|
|
41
44
|
|
|
42
|
-
function SchemaType(path, options, instance) {
|
|
45
|
+
function SchemaType(path, options, instance, parentSchema) {
|
|
43
46
|
this[schemaTypeSymbol] = true;
|
|
44
47
|
this.path = path;
|
|
45
48
|
this.instance = instance;
|
|
49
|
+
this.schemaName = this.constructor.schemaName;
|
|
46
50
|
this.validators = [];
|
|
47
|
-
this.getters = this.constructor
|
|
51
|
+
this.getters = Object.hasOwn(this.constructor, 'getters') ?
|
|
48
52
|
this.constructor.getters.slice() :
|
|
49
53
|
[];
|
|
50
|
-
this.setters =
|
|
54
|
+
this.setters = Object.hasOwn(this.constructor, 'setters') ?
|
|
55
|
+
this.constructor.setters.slice() :
|
|
56
|
+
[];
|
|
51
57
|
|
|
52
58
|
this.splitPath();
|
|
53
59
|
|
|
@@ -56,7 +62,9 @@ function SchemaType(path, options, instance) {
|
|
|
56
62
|
const defaultOptionsKeys = Object.keys(defaultOptions);
|
|
57
63
|
|
|
58
64
|
for (const option of defaultOptionsKeys) {
|
|
59
|
-
if (
|
|
65
|
+
if (option === 'validate') {
|
|
66
|
+
this.validate(defaultOptions.validate);
|
|
67
|
+
} else if (Object.hasOwn(defaultOptions, option) && !Object.hasOwn(options, option)) {
|
|
60
68
|
options[option] = defaultOptions[option];
|
|
61
69
|
}
|
|
62
70
|
}
|
|
@@ -67,9 +75,9 @@ function SchemaType(path, options, instance) {
|
|
|
67
75
|
|
|
68
76
|
const Options = this.OptionsConstructor || SchemaTypeOptions;
|
|
69
77
|
this.options = new Options(options);
|
|
78
|
+
this.parentSchema = parentSchema;
|
|
70
79
|
this._index = null;
|
|
71
80
|
|
|
72
|
-
|
|
73
81
|
if (utils.hasUserDefinedProperty(this.options, 'immutable')) {
|
|
74
82
|
this.$immutable = this.options.immutable;
|
|
75
83
|
|
|
@@ -79,7 +87,11 @@ function SchemaType(path, options, instance) {
|
|
|
79
87
|
const keys = Object.keys(this.options);
|
|
80
88
|
for (const prop of keys) {
|
|
81
89
|
if (prop === 'cast') {
|
|
82
|
-
|
|
90
|
+
if (Array.isArray(this.options[prop])) {
|
|
91
|
+
this.castFunction.apply(this, this.options[prop]);
|
|
92
|
+
} else {
|
|
93
|
+
this.castFunction(this.options[prop]);
|
|
94
|
+
}
|
|
83
95
|
continue;
|
|
84
96
|
}
|
|
85
97
|
if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') {
|
|
@@ -89,11 +101,11 @@ function SchemaType(path, options, instance) {
|
|
|
89
101
|
const index = this._index;
|
|
90
102
|
if (typeof index === 'object' && index != null) {
|
|
91
103
|
if (index.unique) {
|
|
92
|
-
throw new
|
|
104
|
+
throw new MongooseError('Path "' + this.path + '" may not have `index` ' +
|
|
93
105
|
'set to false and `unique` set to true');
|
|
94
106
|
}
|
|
95
107
|
if (index.sparse) {
|
|
96
|
-
throw new
|
|
108
|
+
throw new MongooseError('Path "' + this.path + '" may not have `index` ' +
|
|
97
109
|
'set to false and `sparse` set to true');
|
|
98
110
|
}
|
|
99
111
|
}
|
|
@@ -148,6 +160,87 @@ SchemaType.prototype.OptionsConstructor = SchemaTypeOptions;
|
|
|
148
160
|
|
|
149
161
|
SchemaType.prototype.path;
|
|
150
162
|
|
|
163
|
+
/**
|
|
164
|
+
* Returns a plain JavaScript object representing this SchemaType.
|
|
165
|
+
*
|
|
166
|
+
* Typically used by `JSON.stringify()` or when calling `.toJSON()` on a SchemaType instance.
|
|
167
|
+
* Omits certain internal properties such as `parentSchema` that can cause circular references.
|
|
168
|
+
*
|
|
169
|
+
* #### Example:
|
|
170
|
+
*
|
|
171
|
+
* const schema = new Schema({ name: String });
|
|
172
|
+
* const schematype = schema.path('name');
|
|
173
|
+
* console.log(schematype.toJSON());
|
|
174
|
+
*
|
|
175
|
+
* @memberOf SchemaType
|
|
176
|
+
* @instance
|
|
177
|
+
* @api public
|
|
178
|
+
*/
|
|
179
|
+
|
|
180
|
+
SchemaType.prototype.toJSON = function toJSON() {
|
|
181
|
+
const { parentSchema, ...res } = this;
|
|
182
|
+
return res;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Helper for creating `{ type: 'object' }` vs `{ bsonType: 'object' }` vs nullable variants.
|
|
187
|
+
*
|
|
188
|
+
* @param {string} type
|
|
189
|
+
* @param {string} bsonType
|
|
190
|
+
* @param {object} [options]
|
|
191
|
+
* @param {boolean} [options.useBsonType=false]
|
|
192
|
+
* @param {boolean} [options._defaultRequired=false]
|
|
193
|
+
* @param {boolean} [options._overrideRequired]
|
|
194
|
+
* @returns {object}
|
|
195
|
+
* @api private
|
|
196
|
+
*/
|
|
197
|
+
|
|
198
|
+
SchemaType.prototype._createJSONSchemaTypeDefinition = function _createJSONSchemaTypeDefinition(type, bsonType, options) {
|
|
199
|
+
const useBsonType = options?.useBsonType;
|
|
200
|
+
const isRequired = options?._overrideRequired ??
|
|
201
|
+
(this.options.required == null ?
|
|
202
|
+
(options?._defaultRequired === true || this.path === '_id') :
|
|
203
|
+
this.options.required && typeof this.options.required !== 'function');
|
|
204
|
+
const allowNull = this.options.allowNull !== false;
|
|
205
|
+
|
|
206
|
+
if (useBsonType) {
|
|
207
|
+
if (isRequired || !allowNull) {
|
|
208
|
+
return { bsonType };
|
|
209
|
+
}
|
|
210
|
+
return { bsonType: [bsonType, 'null'] };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (isRequired || !allowNull) {
|
|
214
|
+
return { type };
|
|
215
|
+
}
|
|
216
|
+
return { type: [type, 'null'] };
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Helper for adding this SchemaType's enum values to a JSON schema type definition.
|
|
221
|
+
* Reads `enumValues` rather than `options.enum` because `enum` also accepts an object.
|
|
222
|
+
*
|
|
223
|
+
* @param {object} definition the type definition from `_createJSONSchemaTypeDefinition()`
|
|
224
|
+
* @returns {object} the same definition
|
|
225
|
+
* @api private
|
|
226
|
+
*/
|
|
227
|
+
|
|
228
|
+
SchemaType.prototype._addJSONSchemaEnum = function _addJSONSchemaEnum(definition) {
|
|
229
|
+
if (!Array.isArray(this.enumValues) || this.enumValues.length === 0) {
|
|
230
|
+
return definition;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// The enum validator allows nullish values, so allow `null` wherever the type does.
|
|
234
|
+
// Skip that when the user already listed `null`: MongoDB refuses a `$jsonSchema`
|
|
235
|
+
// whose `enum` repeats a value, and so does Ajv.
|
|
236
|
+
const allowsNull = Array.isArray(definition.type ?? definition.bsonType);
|
|
237
|
+
definition.enum = allowsNull && !this.enumValues.includes(null)
|
|
238
|
+
? [...this.enumValues, null]
|
|
239
|
+
: [...this.enumValues];
|
|
240
|
+
|
|
241
|
+
return definition;
|
|
242
|
+
};
|
|
243
|
+
|
|
151
244
|
/**
|
|
152
245
|
* The validators that Mongoose should run to validate properties at this SchemaType's path.
|
|
153
246
|
*
|
|
@@ -182,9 +275,9 @@ SchemaType.prototype.validators;
|
|
|
182
275
|
SchemaType.prototype.isRequired;
|
|
183
276
|
|
|
184
277
|
/**
|
|
185
|
-
* Split the current
|
|
278
|
+
* Split the current dotted path into segments
|
|
186
279
|
*
|
|
187
|
-
* @return {
|
|
280
|
+
* @return {string[]|undefined}
|
|
188
281
|
* @api private
|
|
189
282
|
*/
|
|
190
283
|
|
|
@@ -252,14 +345,24 @@ SchemaType.cast = function cast(caster) {
|
|
|
252
345
|
* @api public
|
|
253
346
|
*/
|
|
254
347
|
|
|
255
|
-
SchemaType.prototype.castFunction = function castFunction(caster) {
|
|
348
|
+
SchemaType.prototype.castFunction = function castFunction(caster, message) {
|
|
256
349
|
if (arguments.length === 0) {
|
|
257
350
|
return this._castFunction;
|
|
258
351
|
}
|
|
352
|
+
|
|
259
353
|
if (caster === false) {
|
|
260
354
|
caster = this.constructor._defaultCaster || (v => v);
|
|
261
355
|
}
|
|
262
|
-
|
|
356
|
+
if (typeof caster === 'string') {
|
|
357
|
+
this._castErrorMessage = caster;
|
|
358
|
+
return this._castFunction;
|
|
359
|
+
}
|
|
360
|
+
if (caster != null) {
|
|
361
|
+
this._castFunction = caster;
|
|
362
|
+
}
|
|
363
|
+
if (message != null) {
|
|
364
|
+
this._castErrorMessage = message;
|
|
365
|
+
}
|
|
263
366
|
|
|
264
367
|
return this._castFunction;
|
|
265
368
|
};
|
|
@@ -267,14 +370,14 @@ SchemaType.prototype.castFunction = function castFunction(caster) {
|
|
|
267
370
|
/**
|
|
268
371
|
* The function that Mongoose calls to cast arbitrary values to this SchemaType.
|
|
269
372
|
*
|
|
270
|
-
* @param {
|
|
373
|
+
* @param {object} value value to cast
|
|
271
374
|
* @param {Document} doc document that triggers the casting
|
|
272
|
-
* @param {
|
|
375
|
+
* @param {boolean} init
|
|
273
376
|
* @api public
|
|
274
377
|
*/
|
|
275
378
|
|
|
276
379
|
SchemaType.prototype.cast = function cast() {
|
|
277
|
-
throw new
|
|
380
|
+
throw new MongooseError('Base SchemaType class does not implement a `cast()` function');
|
|
278
381
|
};
|
|
279
382
|
|
|
280
383
|
/**
|
|
@@ -285,8 +388,8 @@ SchemaType.prototype.cast = function cast() {
|
|
|
285
388
|
* // Make all strings be trimmed by default
|
|
286
389
|
* mongoose.SchemaTypes.String.set('trim', true);
|
|
287
390
|
*
|
|
288
|
-
* @param {
|
|
289
|
-
* @param {
|
|
391
|
+
* @param {string} option The name of the option you'd like to set (e.g. trim, lowercase, etc...)
|
|
392
|
+
* @param {any} value The value of the option you'd like to set.
|
|
290
393
|
* @return {void}
|
|
291
394
|
* @static
|
|
292
395
|
* @memberOf SchemaType
|
|
@@ -295,7 +398,7 @@ SchemaType.prototype.cast = function cast() {
|
|
|
295
398
|
*/
|
|
296
399
|
|
|
297
400
|
SchemaType.set = function set(option, value) {
|
|
298
|
-
if (!
|
|
401
|
+
if (!Object.hasOwn(this, 'defaultOptions')) {
|
|
299
402
|
this.defaultOptions = Object.assign({}, this.defaultOptions);
|
|
300
403
|
}
|
|
301
404
|
this.defaultOptions[option] = value;
|
|
@@ -318,7 +421,7 @@ SchemaType.set = function set(option, value) {
|
|
|
318
421
|
*/
|
|
319
422
|
|
|
320
423
|
SchemaType.get = function(getter) {
|
|
321
|
-
this.getters =
|
|
424
|
+
this.getters = Object.hasOwn(this, 'getters') ? this.getters : [];
|
|
322
425
|
this.getters.push(getter);
|
|
323
426
|
};
|
|
324
427
|
|
|
@@ -337,10 +440,10 @@ SchemaType.get = function(getter) {
|
|
|
337
440
|
* #### Example:
|
|
338
441
|
*
|
|
339
442
|
* // values are cast:
|
|
340
|
-
* const schema = new Schema({
|
|
443
|
+
* const schema = new Schema({ num: { type: Number, default: 4.815162342 }})
|
|
341
444
|
* const M = db.model('M', schema)
|
|
342
445
|
* const m = new M;
|
|
343
|
-
* console.log(m.
|
|
446
|
+
* console.log(m.num) // 4.815162342
|
|
344
447
|
*
|
|
345
448
|
* // default unique objects for Mixed types:
|
|
346
449
|
* const schema = new Schema({ mixed: Schema.Types.Mixed });
|
|
@@ -361,7 +464,7 @@ SchemaType.get = function(getter) {
|
|
|
361
464
|
* console.log(m2.mixed); // { added: 1 }
|
|
362
465
|
*
|
|
363
466
|
* @param {Function|any} val The default value to set
|
|
364
|
-
* @return {
|
|
467
|
+
* @return {any|undefined} Returns the set default value.
|
|
365
468
|
* @api public
|
|
366
469
|
*/
|
|
367
470
|
|
|
@@ -372,7 +475,7 @@ SchemaType.prototype.default = function(val) {
|
|
|
372
475
|
return void 0;
|
|
373
476
|
}
|
|
374
477
|
|
|
375
|
-
if (val
|
|
478
|
+
if (val?.instanceOfSchema) {
|
|
376
479
|
throw new MongooseError('Cannot set default value of path `' + this.path +
|
|
377
480
|
'` to a mongoose Schema instance.');
|
|
378
481
|
}
|
|
@@ -400,14 +503,7 @@ SchemaType.prototype.default = function(val) {
|
|
|
400
503
|
* s.path('my.date').index({ expires: 60 });
|
|
401
504
|
* s.path('my.path').index({ unique: true, sparse: true });
|
|
402
505
|
*
|
|
403
|
-
*
|
|
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
|
|
506
|
+
* @param {object|boolean|string|number} options
|
|
411
507
|
* @return {SchemaType} this
|
|
412
508
|
* @api public
|
|
413
509
|
*/
|
|
@@ -428,21 +524,38 @@ SchemaType.prototype.index = function(options) {
|
|
|
428
524
|
*
|
|
429
525
|
* _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
|
|
430
526
|
*
|
|
431
|
-
*
|
|
527
|
+
* You can optionally specify an error message to replace MongoDB's default `E11000 duplicate key error` message.
|
|
528
|
+
* The following will throw a "Email must be unique" error if `save()`, `updateOne()`, `updateMany()`, `replaceOne()`,
|
|
529
|
+
* `findOneAndUpdate()`, or `findOneAndReplace()` throws a duplicate key error:
|
|
530
|
+
*
|
|
531
|
+
* ```javascript
|
|
532
|
+
* new Schema({
|
|
533
|
+
* email: {
|
|
534
|
+
* type: String,
|
|
535
|
+
* unique: [true, 'Email must be unique']
|
|
536
|
+
* }
|
|
537
|
+
* });
|
|
538
|
+
* ```
|
|
539
|
+
*
|
|
540
|
+
* Note that the above syntax does **not** work for `bulkWrite()` or `insertMany()`. `bulkWrite()` and `insertMany()`
|
|
541
|
+
* will still throw MongoDB's default `E11000 duplicate key error` message.
|
|
542
|
+
*
|
|
543
|
+
* @param {boolean} value
|
|
544
|
+
* @param {string} [message]
|
|
432
545
|
* @return {SchemaType} this
|
|
433
546
|
* @api public
|
|
434
547
|
*/
|
|
435
548
|
|
|
436
|
-
SchemaType.prototype.unique = function(
|
|
549
|
+
SchemaType.prototype.unique = function unique(value, message) {
|
|
437
550
|
if (this._index === false) {
|
|
438
|
-
if (!
|
|
551
|
+
if (!value) {
|
|
439
552
|
return;
|
|
440
553
|
}
|
|
441
|
-
throw new
|
|
554
|
+
throw new MongooseError('Path "' + this.path + '" may not have `index` set to ' +
|
|
442
555
|
'false and `unique` set to true');
|
|
443
556
|
}
|
|
444
557
|
|
|
445
|
-
if (!this.options
|
|
558
|
+
if (!Object.hasOwn(this.options, 'index') && value === false) {
|
|
446
559
|
return this;
|
|
447
560
|
}
|
|
448
561
|
|
|
@@ -452,7 +565,10 @@ SchemaType.prototype.unique = function(bool) {
|
|
|
452
565
|
this._index = { type: this._index };
|
|
453
566
|
}
|
|
454
567
|
|
|
455
|
-
this._index.unique =
|
|
568
|
+
this._index.unique = !!value;
|
|
569
|
+
if (typeof message === 'string') {
|
|
570
|
+
this._duplicateKeyErrorMessage = message;
|
|
571
|
+
}
|
|
456
572
|
return this;
|
|
457
573
|
};
|
|
458
574
|
|
|
@@ -464,7 +580,7 @@ SchemaType.prototype.unique = function(bool) {
|
|
|
464
580
|
* const s = new Schema({ name : { type: String, text : true } })
|
|
465
581
|
* s.path('name').index({ text : true });
|
|
466
582
|
*
|
|
467
|
-
* @param {
|
|
583
|
+
* @param {boolean} bool
|
|
468
584
|
* @return {SchemaType} this
|
|
469
585
|
* @api public
|
|
470
586
|
*/
|
|
@@ -474,11 +590,11 @@ SchemaType.prototype.text = function(bool) {
|
|
|
474
590
|
if (!bool) {
|
|
475
591
|
return this;
|
|
476
592
|
}
|
|
477
|
-
throw new
|
|
593
|
+
throw new MongooseError('Path "' + this.path + '" may not have `index` set to ' +
|
|
478
594
|
'false and `text` set to true');
|
|
479
595
|
}
|
|
480
596
|
|
|
481
|
-
if (!this.options
|
|
597
|
+
if (!Object.hasOwn(this.options, 'index') && bool === false) {
|
|
482
598
|
return this;
|
|
483
599
|
}
|
|
484
600
|
|
|
@@ -501,7 +617,7 @@ SchemaType.prototype.text = function(bool) {
|
|
|
501
617
|
* const s = new Schema({ name: { type: String, sparse: true } });
|
|
502
618
|
* s.path('name').index({ sparse: true });
|
|
503
619
|
*
|
|
504
|
-
* @param {
|
|
620
|
+
* @param {boolean} bool
|
|
505
621
|
* @return {SchemaType} this
|
|
506
622
|
* @api public
|
|
507
623
|
*/
|
|
@@ -511,11 +627,11 @@ SchemaType.prototype.sparse = function(bool) {
|
|
|
511
627
|
if (!bool) {
|
|
512
628
|
return this;
|
|
513
629
|
}
|
|
514
|
-
throw new
|
|
630
|
+
throw new MongooseError('Path "' + this.path + '" may not have `index` set to ' +
|
|
515
631
|
'false and `sparse` set to true');
|
|
516
632
|
}
|
|
517
633
|
|
|
518
|
-
if (!this.options
|
|
634
|
+
if (!Object.hasOwn(this.options, 'index') && bool === false) {
|
|
519
635
|
return this;
|
|
520
636
|
}
|
|
521
637
|
|
|
@@ -531,7 +647,7 @@ SchemaType.prototype.sparse = function(bool) {
|
|
|
531
647
|
|
|
532
648
|
/**
|
|
533
649
|
* Defines this path as immutable. Mongoose prevents you from changing
|
|
534
|
-
* immutable paths unless the parent document has [`isNew: true`](/docs/api/document.html#
|
|
650
|
+
* immutable paths unless the parent document has [`isNew: true`](https://mongoosejs.com/docs/api/document.html#Document.prototype.isNew).
|
|
535
651
|
*
|
|
536
652
|
* #### Example:
|
|
537
653
|
*
|
|
@@ -549,7 +665,7 @@ SchemaType.prototype.sparse = function(bool) {
|
|
|
549
665
|
* doc.name; // 'test', because `name` is immutable
|
|
550
666
|
*
|
|
551
667
|
* Mongoose also prevents changing immutable properties using `updateOne()`
|
|
552
|
-
* and `updateMany()` based on [strict mode](/docs/guide.html#strict).
|
|
668
|
+
* and `updateMany()` based on [strict mode](https://mongoosejs.com/docs/guide.html#strict).
|
|
553
669
|
*
|
|
554
670
|
* #### Example:
|
|
555
671
|
*
|
|
@@ -566,9 +682,9 @@ SchemaType.prototype.sparse = function(bool) {
|
|
|
566
682
|
* // the property is immutable.
|
|
567
683
|
* Model.updateOne({}, { name: 'test2' }, { strict: false });
|
|
568
684
|
*
|
|
569
|
-
* @param {
|
|
685
|
+
* @param {boolean} bool
|
|
570
686
|
* @return {SchemaType} this
|
|
571
|
-
* @see isNew /docs/api/document.html#
|
|
687
|
+
* @see isNew https://mongoosejs.com/docs/api/document.html#Document.prototype.isNew
|
|
572
688
|
* @api public
|
|
573
689
|
*/
|
|
574
690
|
|
|
@@ -657,10 +773,13 @@ SchemaType.prototype.transform = function(fn) {
|
|
|
657
773
|
* console.log(user.email); // 'avenue@q.com'
|
|
658
774
|
* User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'
|
|
659
775
|
*
|
|
776
|
+
* // Setters also transform query filters
|
|
777
|
+
* const user = await User.find({ email: 'AVENUE@Q.COM' }); // query for 'avenue@q.com'
|
|
778
|
+
*
|
|
660
779
|
* As you can see above, setters allow you to transform the data before it
|
|
661
780
|
* stored in MongoDB, or before executing a query.
|
|
662
781
|
*
|
|
663
|
-
* _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._
|
|
782
|
+
* _NOTE: we could have also just used the built-in [`lowercase: true` SchemaType option](https://mongoosejs.com/docs/api/schemastringoptions.html#SchemaStringOptions.prototype.lowercase) instead of defining our own function._
|
|
664
783
|
*
|
|
665
784
|
* new Schema({ email: { type: String, lowercase: true }})
|
|
666
785
|
*
|
|
@@ -727,7 +846,7 @@ SchemaType.prototype.set = function(fn) {
|
|
|
727
846
|
* // defining within the schema
|
|
728
847
|
* const s = new Schema({ born: { type: Date, get: dob })
|
|
729
848
|
*
|
|
730
|
-
* // or by
|
|
849
|
+
* // or by retrieving its SchemaType
|
|
731
850
|
* const s = new Schema({ born: Date })
|
|
732
851
|
* s.path('born').get(dob)
|
|
733
852
|
*
|
|
@@ -784,6 +903,21 @@ SchemaType.prototype.get = function(fn) {
|
|
|
784
903
|
return this;
|
|
785
904
|
};
|
|
786
905
|
|
|
906
|
+
/**
|
|
907
|
+
* Adds multiple validators for this document path.
|
|
908
|
+
* Calls `validate()` for every element in validators.
|
|
909
|
+
*
|
|
910
|
+
* @param {(RegExp|Function|object)[]} validators
|
|
911
|
+
* @returns {SchemaType}
|
|
912
|
+
*/
|
|
913
|
+
|
|
914
|
+
SchemaType.prototype.validateAll = function(validators) {
|
|
915
|
+
for (let i = 0; i < validators.length; i++) {
|
|
916
|
+
this.validate(validators[i]);
|
|
917
|
+
}
|
|
918
|
+
return this;
|
|
919
|
+
};
|
|
920
|
+
|
|
787
921
|
/**
|
|
788
922
|
* Adds validator(s) for this document path.
|
|
789
923
|
*
|
|
@@ -791,7 +925,7 @@ SchemaType.prototype.get = function(fn) {
|
|
|
791
925
|
* must return `Boolean`. Returning `false` or throwing an error means
|
|
792
926
|
* validation failed.
|
|
793
927
|
*
|
|
794
|
-
* The error message argument is optional. If not passed, the [default generic error message template](#
|
|
928
|
+
* The error message argument is optional. If not passed, the [default generic error message template](https://mongoosejs.com/docs/api/error.html#Error.messages) will be used.
|
|
795
929
|
*
|
|
796
930
|
* #### Example:
|
|
797
931
|
*
|
|
@@ -809,8 +943,8 @@ SchemaType.prototype.get = function(fn) {
|
|
|
809
943
|
* // adding many validators at a time
|
|
810
944
|
*
|
|
811
945
|
* const many = [
|
|
812
|
-
* { validator: validator,
|
|
813
|
-
* , { validator: anotherValidator,
|
|
946
|
+
* { validator: validator, message: 'uh oh' }
|
|
947
|
+
* , { validator: anotherValidator, message: 'failed' }
|
|
814
948
|
* ]
|
|
815
949
|
* new Schema({ name: { type: String, validate: many }});
|
|
816
950
|
*
|
|
@@ -821,10 +955,12 @@ SchemaType.prototype.get = function(fn) {
|
|
|
821
955
|
*
|
|
822
956
|
* #### Error message templates:
|
|
823
957
|
*
|
|
824
|
-
*
|
|
825
|
-
*
|
|
826
|
-
*
|
|
827
|
-
*
|
|
958
|
+
* Below is a list of supported template keywords:
|
|
959
|
+
*
|
|
960
|
+
* - PATH: The schema path where the error is being triggered.
|
|
961
|
+
* - VALUE: The value assigned to the PATH that is triggering the error.
|
|
962
|
+
* - KIND: The validation property that triggered the error i.e. required.
|
|
963
|
+
* - REASON: The error object that caused this error if there was one.
|
|
828
964
|
*
|
|
829
965
|
* If Mongoose's built-in error message templating isn't enough, Mongoose
|
|
830
966
|
* supports setting the `message` property to a function.
|
|
@@ -842,7 +978,7 @@ SchemaType.prototype.get = function(fn) {
|
|
|
842
978
|
*
|
|
843
979
|
* schema.path('name').validate({
|
|
844
980
|
* validator: function() { throw new Error('Oops!'); },
|
|
845
|
-
* // `errors['name']` will be "Oops!"
|
|
981
|
+
* // `errors['name'].message` will be "Oops!"
|
|
846
982
|
* message: function(props) { return props.reason.message; }
|
|
847
983
|
* });
|
|
848
984
|
*
|
|
@@ -860,11 +996,11 @@ SchemaType.prototype.get = function(fn) {
|
|
|
860
996
|
* }
|
|
861
997
|
* });
|
|
862
998
|
*
|
|
863
|
-
* You might use asynchronous validators to
|
|
999
|
+
* You might use asynchronous validators to retrieve other documents from the database to validate against or to meet other I/O bound validation needs.
|
|
864
1000
|
*
|
|
865
|
-
* Validation occurs `pre('save')` or whenever you manually execute [document#validate](#
|
|
1001
|
+
* Validation occurs `pre('save')` or whenever you manually execute [document#validate](https://mongoosejs.com/docs/api/document.html#Document.prototype.validate()).
|
|
866
1002
|
*
|
|
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](#
|
|
1003
|
+
* 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](https://mongoosejs.com/docs/api/connection.html#Connection()), passing the validation error object along.
|
|
868
1004
|
*
|
|
869
1005
|
* const conn = mongoose.createConnection(..);
|
|
870
1006
|
* conn.on('error', handleError);
|
|
@@ -879,12 +1015,12 @@ SchemaType.prototype.get = function(fn) {
|
|
|
879
1015
|
* // registering an error listener on the Model lets us handle errors more locally
|
|
880
1016
|
* Product.on('error', handleError);
|
|
881
1017
|
*
|
|
882
|
-
* @param {RegExp|Function|
|
|
1018
|
+
* @param {RegExp|Function|object} obj validator function, or hash describing options
|
|
883
1019
|
* @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 {
|
|
885
|
-
* @param {
|
|
886
|
-
* @param {
|
|
887
|
-
* @param {
|
|
1020
|
+
* @param {string|Function} [obj.message] optional error message. If function, should return the error message as a string
|
|
1021
|
+
* @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.
|
|
1022
|
+
* @param {string|Function} [errorMsg] optional error message. If function, should return the error message as a string
|
|
1023
|
+
* @param {string} [type] optional validator type
|
|
888
1024
|
* @return {SchemaType} this
|
|
889
1025
|
* @api public
|
|
890
1026
|
*/
|
|
@@ -896,7 +1032,7 @@ SchemaType.prototype.validate = function(obj, message, type) {
|
|
|
896
1032
|
properties = { validator: obj, message: message };
|
|
897
1033
|
properties.type = type || 'user defined';
|
|
898
1034
|
} else if (message instanceof Object && !type) {
|
|
899
|
-
properties = isSimpleValidator(message) ? Object.assign({}, message) :
|
|
1035
|
+
properties = isSimpleValidator(message) ? Object.assign({}, message) : clone(message);
|
|
900
1036
|
if (!properties.message) {
|
|
901
1037
|
properties.message = properties.msg;
|
|
902
1038
|
}
|
|
@@ -925,9 +1061,9 @@ SchemaType.prototype.validate = function(obj, message, type) {
|
|
|
925
1061
|
if (!utils.isPOJO(arg)) {
|
|
926
1062
|
const msg = 'Invalid validator. Received (' + typeof arg + ') '
|
|
927
1063
|
+ arg
|
|
928
|
-
+ '. See https://mongoosejs.com/docs/api/schematype.html#
|
|
1064
|
+
+ '. See https://mongoosejs.com/docs/api/schematype.html#SchemaType.prototype.validate()';
|
|
929
1065
|
|
|
930
|
-
throw new
|
|
1066
|
+
throw new MongooseError(msg);
|
|
931
1067
|
}
|
|
932
1068
|
this.validate(arg.validator, arg);
|
|
933
1069
|
}
|
|
@@ -987,18 +1123,18 @@ SchemaType.prototype.validate = function(obj, message, type) {
|
|
|
987
1123
|
* the value is not null nor undefined). However, most built-in mongoose schema
|
|
988
1124
|
* types override the default `checkRequired` function:
|
|
989
1125
|
*
|
|
990
|
-
* @param {
|
|
991
|
-
* @param {
|
|
1126
|
+
* @param {boolean|Function|object} required enable/disable the validator, or function that returns required boolean, or options object
|
|
1127
|
+
* @param {boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean
|
|
992
1128
|
* @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.
|
|
993
|
-
* @param {
|
|
1129
|
+
* @param {string} [message] optional custom error message
|
|
994
1130
|
* @return {SchemaType} this
|
|
995
|
-
* @see Customized Error Messages #
|
|
996
|
-
* @see SchemaArray#checkRequired #
|
|
997
|
-
* @see SchemaBoolean#checkRequired #
|
|
998
|
-
* @see SchemaBuffer#checkRequired #
|
|
999
|
-
* @see SchemaNumber#checkRequired #
|
|
1000
|
-
* @see SchemaObjectId#checkRequired #
|
|
1001
|
-
* @see SchemaString#checkRequired #
|
|
1131
|
+
* @see Customized Error Messages https://mongoosejs.com/docs/api/error.html#Error.messages
|
|
1132
|
+
* @see SchemaArray#checkRequired https://mongoosejs.com/docs/api/schemaarray.html#SchemaArray.prototype.checkRequired()
|
|
1133
|
+
* @see SchemaBoolean#checkRequired https://mongoosejs.com/docs/api/schemaboolean.html#SchemaBoolean.prototype.checkRequired()
|
|
1134
|
+
* @see SchemaBuffer#checkRequired https://mongoosejs.com/docs/api/schemabuffer.html#SchemaBuffer.prototype.checkRequired()
|
|
1135
|
+
* @see SchemaNumber#checkRequired https://mongoosejs.com/docs/api/schemanumber.html#SchemaNumber.prototype.checkRequired()
|
|
1136
|
+
* @see SchemaObjectId#checkRequired https://mongoosejs.com/docs/api/schemaobjectid.html#SchemaObjectId.prototype.checkRequired()
|
|
1137
|
+
* @see SchemaString#checkRequired https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.checkRequired()
|
|
1002
1138
|
* @api public
|
|
1003
1139
|
*/
|
|
1004
1140
|
|
|
@@ -1033,16 +1169,22 @@ SchemaType.prototype.required = function(required, message) {
|
|
|
1033
1169
|
|
|
1034
1170
|
const _this = this;
|
|
1035
1171
|
this.isRequired = true;
|
|
1172
|
+
this.originalRequiredValue = required;
|
|
1173
|
+
|
|
1174
|
+
if (typeof this.originalRequiredValue !== 'function' &&
|
|
1175
|
+
(utils.hasUserDefinedProperty(this.options, 'allowNull') || this.allowNullValidator != null)) {
|
|
1176
|
+
throw new MongooseError('Path "' + this.path + '" may not have `allowNull` specified when `required` is true');
|
|
1177
|
+
}
|
|
1036
1178
|
|
|
1037
1179
|
this.requiredValidator = function(v) {
|
|
1038
|
-
const cachedRequired = this
|
|
1180
|
+
const cachedRequired = this?.$__?.cachedRequired;
|
|
1039
1181
|
|
|
1040
1182
|
// no validation when this path wasn't selected in the query.
|
|
1041
1183
|
if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) {
|
|
1042
1184
|
return true;
|
|
1043
1185
|
}
|
|
1044
1186
|
|
|
1045
|
-
// `$cachedRequired` gets set in `
|
|
1187
|
+
// `$cachedRequired` gets set in `_getPathsToValidate()` so we
|
|
1046
1188
|
// don't call required functions multiple times in one validate call
|
|
1047
1189
|
// See gh-6801
|
|
1048
1190
|
if (cachedRequired != null && _this.path in cachedRequired) {
|
|
@@ -1057,8 +1199,6 @@ SchemaType.prototype.required = function(required, message) {
|
|
|
1057
1199
|
|
|
1058
1200
|
return _this.checkRequired(v, this);
|
|
1059
1201
|
};
|
|
1060
|
-
this.originalRequiredValue = required;
|
|
1061
|
-
|
|
1062
1202
|
if (typeof required === 'string') {
|
|
1063
1203
|
message = required;
|
|
1064
1204
|
required = undefined;
|
|
@@ -1074,6 +1214,54 @@ SchemaType.prototype.required = function(required, message) {
|
|
|
1074
1214
|
return this;
|
|
1075
1215
|
};
|
|
1076
1216
|
|
|
1217
|
+
/**
|
|
1218
|
+
* Adds a validator that disallows `null` for this path without making the path
|
|
1219
|
+
* required. `undefined` values still pass validation.
|
|
1220
|
+
*
|
|
1221
|
+
* #### Example:
|
|
1222
|
+
*
|
|
1223
|
+
* const schema = new Schema({
|
|
1224
|
+
* name: { type: String, allowNull: false }
|
|
1225
|
+
* });
|
|
1226
|
+
*
|
|
1227
|
+
* new Model({}).validateSync(); // OK
|
|
1228
|
+
* new Model({ name: undefined }).validateSync(); // OK, Mongoose strips out `name` when its value is `undefined`
|
|
1229
|
+
* new Model({ name: null }).validateSync(); // ValidationError
|
|
1230
|
+
*
|
|
1231
|
+
* @param {boolean} allowNull
|
|
1232
|
+
* @return {SchemaType} this
|
|
1233
|
+
* @api public
|
|
1234
|
+
*/
|
|
1235
|
+
|
|
1236
|
+
SchemaType.prototype.allowNull = function(allowNull) {
|
|
1237
|
+
if (arguments.length > 0 && this.isRequired && typeof this.originalRequiredValue !== 'function') {
|
|
1238
|
+
throw new MongooseError('Path "' + this.path + '" may not have `allowNull` specified when `required` is true');
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
this.validators = this.validators.filter(function(v) {
|
|
1242
|
+
return v.validator !== this.allowNullValidator;
|
|
1243
|
+
}, this);
|
|
1244
|
+
|
|
1245
|
+
if (allowNull !== false) {
|
|
1246
|
+
delete this.options.allowNull;
|
|
1247
|
+
delete this.allowNullValidator;
|
|
1248
|
+
return this;
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
this.options.allowNull = false;
|
|
1252
|
+
this.allowNullValidator = function(v) {
|
|
1253
|
+
return v !== null;
|
|
1254
|
+
};
|
|
1255
|
+
|
|
1256
|
+
this.validators.push({
|
|
1257
|
+
validator: this.allowNullValidator,
|
|
1258
|
+
message: MongooseError.messages.general.allowNull,
|
|
1259
|
+
type: 'allowNull'
|
|
1260
|
+
});
|
|
1261
|
+
|
|
1262
|
+
return this;
|
|
1263
|
+
};
|
|
1264
|
+
|
|
1077
1265
|
/**
|
|
1078
1266
|
* Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
|
|
1079
1267
|
* looks at to determine the foreign collection it should query.
|
|
@@ -1094,7 +1282,7 @@ SchemaType.prototype.required = function(required, message) {
|
|
|
1094
1282
|
* user: { type: mongoose.ObjectId, ref: User }
|
|
1095
1283
|
* });
|
|
1096
1284
|
*
|
|
1097
|
-
* @param {
|
|
1285
|
+
* @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
1286
|
* @return {SchemaType} this
|
|
1099
1287
|
* @api public
|
|
1100
1288
|
*/
|
|
@@ -1107,40 +1295,59 @@ SchemaType.prototype.ref = function(ref) {
|
|
|
1107
1295
|
/**
|
|
1108
1296
|
* Gets the default value
|
|
1109
1297
|
*
|
|
1110
|
-
* @param {
|
|
1111
|
-
* @param {
|
|
1112
|
-
* @
|
|
1298
|
+
* @param {object} parentDoc
|
|
1299
|
+
* @param {boolean} init
|
|
1300
|
+
* @param {object} options
|
|
1301
|
+
* @param {object} [options.context]
|
|
1302
|
+
* @param {boolean} [options.skipCast]
|
|
1303
|
+
* @param {object} [applySettersOptions] passed to applySetters
|
|
1304
|
+
* @return {any} The Stored default value.
|
|
1113
1305
|
* @api private
|
|
1114
1306
|
*/
|
|
1115
1307
|
|
|
1116
|
-
SchemaType.prototype.getDefault = function(
|
|
1308
|
+
SchemaType.prototype.getDefault = function getDefault(parentDoc, init, options, applySettersOptions) {
|
|
1117
1309
|
let ret;
|
|
1310
|
+
if (this.defaultValue == null) {
|
|
1311
|
+
return this.defaultValue;
|
|
1312
|
+
}
|
|
1118
1313
|
if (typeof this.defaultValue === 'function') {
|
|
1314
|
+
// In setDefaultsOnInsert, we pass the Query as `context` option. This is used to
|
|
1315
|
+
// avoid passing the query as the parent doc to `applySetters()` below, because
|
|
1316
|
+
// applySetters assumes parentDoc is a document or null. Queries run setters
|
|
1317
|
+
// separately anyway.
|
|
1318
|
+
const context = options?.context ?? parentDoc;
|
|
1119
1319
|
if (
|
|
1120
1320
|
this.defaultValue === Date.now ||
|
|
1121
1321
|
this.defaultValue === Array ||
|
|
1122
|
-
this.defaultValue.name
|
|
1322
|
+
this.defaultValue.name === 'ObjectId' ||
|
|
1323
|
+
this.defaultValue.name === 'ObjectID'
|
|
1123
1324
|
) {
|
|
1124
|
-
ret = this.defaultValue.call(
|
|
1325
|
+
ret = this.defaultValue.call(context);
|
|
1125
1326
|
} else {
|
|
1126
|
-
ret = this.defaultValue.call(
|
|
1327
|
+
ret = this.defaultValue.call(context, context);
|
|
1127
1328
|
}
|
|
1128
1329
|
} else {
|
|
1129
1330
|
ret = this.defaultValue;
|
|
1130
1331
|
}
|
|
1131
1332
|
|
|
1132
|
-
if (ret
|
|
1133
|
-
if (typeof ret === 'object' &&
|
|
1134
|
-
ret =
|
|
1333
|
+
if (ret != null) {
|
|
1334
|
+
if (typeof ret === 'object' && ret != null && ret._bsontype !== 'ObjectId' && !this.options?.shared) {
|
|
1335
|
+
ret = clone(ret);
|
|
1135
1336
|
}
|
|
1136
1337
|
|
|
1137
|
-
if (options
|
|
1138
|
-
return this._applySetters(ret,
|
|
1338
|
+
if (options?.skipCast) {
|
|
1339
|
+
return this._applySetters(ret, parentDoc);
|
|
1139
1340
|
}
|
|
1140
1341
|
|
|
1141
|
-
const casted = this.applySetters(
|
|
1342
|
+
const casted = this.applySetters(
|
|
1343
|
+
ret,
|
|
1344
|
+
parentDoc,
|
|
1345
|
+
init,
|
|
1346
|
+
undefined,
|
|
1347
|
+
applySettersOptions ?? setOptionsForDefaults
|
|
1348
|
+
);
|
|
1142
1349
|
if (casted && !Array.isArray(casted) && casted.$isSingleNested) {
|
|
1143
|
-
casted.$__parent =
|
|
1350
|
+
casted.$__parent = parentDoc;
|
|
1144
1351
|
}
|
|
1145
1352
|
return casted;
|
|
1146
1353
|
}
|
|
@@ -1150,11 +1357,11 @@ SchemaType.prototype.getDefault = function(scope, init, options) {
|
|
|
1150
1357
|
/**
|
|
1151
1358
|
* Applies setters without casting
|
|
1152
1359
|
*
|
|
1153
|
-
* @param {
|
|
1154
|
-
* @param {
|
|
1155
|
-
* @param {
|
|
1156
|
-
* @param {
|
|
1157
|
-
* @param {
|
|
1360
|
+
* @param {any} value
|
|
1361
|
+
* @param {any} scope
|
|
1362
|
+
* @param {boolean} init
|
|
1363
|
+
* @param {any} priorVal
|
|
1364
|
+
* @param {object} [options]
|
|
1158
1365
|
* @instance
|
|
1159
1366
|
* @api private
|
|
1160
1367
|
*/
|
|
@@ -1184,10 +1391,10 @@ SchemaType.prototype._castNullish = function _castNullish(v) {
|
|
|
1184
1391
|
/**
|
|
1185
1392
|
* Applies setters
|
|
1186
1393
|
*
|
|
1187
|
-
* @param {
|
|
1188
|
-
* @param {
|
|
1189
|
-
* @param {
|
|
1190
|
-
* @return {
|
|
1394
|
+
* @param {any} value
|
|
1395
|
+
* @param {object} scope
|
|
1396
|
+
* @param {boolean} init
|
|
1397
|
+
* @return {any}
|
|
1191
1398
|
* @api private
|
|
1192
1399
|
*/
|
|
1193
1400
|
|
|
@@ -1196,7 +1403,6 @@ SchemaType.prototype.applySetters = function(value, scope, init, priorVal, optio
|
|
|
1196
1403
|
if (v == null) {
|
|
1197
1404
|
return this._castNullish(v);
|
|
1198
1405
|
}
|
|
1199
|
-
|
|
1200
1406
|
// do not cast until all setters are applied #665
|
|
1201
1407
|
v = this.cast(v, scope, init, priorVal, options);
|
|
1202
1408
|
|
|
@@ -1206,9 +1412,9 @@ SchemaType.prototype.applySetters = function(value, scope, init, priorVal, optio
|
|
|
1206
1412
|
/**
|
|
1207
1413
|
* Applies getters to a value
|
|
1208
1414
|
*
|
|
1209
|
-
* @param {
|
|
1210
|
-
* @param {
|
|
1211
|
-
* @return {
|
|
1415
|
+
* @param {object} value
|
|
1416
|
+
* @param {object} scope
|
|
1417
|
+
* @return {any}
|
|
1212
1418
|
* @api private
|
|
1213
1419
|
*/
|
|
1214
1420
|
|
|
@@ -1240,7 +1446,7 @@ SchemaType.prototype.applyGetters = function(value, scope) {
|
|
|
1240
1446
|
* // .. unless overridden;
|
|
1241
1447
|
* T.find().select('-x').exec(callback);
|
|
1242
1448
|
*
|
|
1243
|
-
* @param {
|
|
1449
|
+
* @param {boolean} val
|
|
1244
1450
|
* @return {SchemaType} this
|
|
1245
1451
|
* @api public
|
|
1246
1452
|
*/
|
|
@@ -1253,16 +1459,15 @@ SchemaType.prototype.select = function select(val) {
|
|
|
1253
1459
|
/**
|
|
1254
1460
|
* Performs a validation of `value` using the validators declared for this SchemaType.
|
|
1255
1461
|
*
|
|
1256
|
-
* @param {
|
|
1257
|
-
* @param {
|
|
1258
|
-
* @param {
|
|
1259
|
-
* @param {
|
|
1260
|
-
* @
|
|
1261
|
-
* @return {Any} If no validators, returns the output from calling `fn`, otherwise no return
|
|
1462
|
+
* @param {any} value
|
|
1463
|
+
* @param {object} scope
|
|
1464
|
+
* @param {object} [options]
|
|
1465
|
+
* @param {string} [options.path]
|
|
1466
|
+
* @return {any} If no validators, returns the output from calling `fn`, otherwise no return
|
|
1262
1467
|
* @api public
|
|
1263
1468
|
*/
|
|
1264
1469
|
|
|
1265
|
-
SchemaType.prototype.doValidate = function(value,
|
|
1470
|
+
SchemaType.prototype.doValidate = async function doValidate(value, scope, options) {
|
|
1266
1471
|
let err = false;
|
|
1267
1472
|
const path = this.path;
|
|
1268
1473
|
|
|
@@ -1270,37 +1475,37 @@ SchemaType.prototype.doValidate = function(value, fn, scope, options) {
|
|
|
1270
1475
|
const validators = this.validators.
|
|
1271
1476
|
filter(v => typeof v === 'object' && v !== null);
|
|
1272
1477
|
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
if (!count) {
|
|
1276
|
-
return fn(null);
|
|
1478
|
+
if (!validators.length) {
|
|
1479
|
+
return;
|
|
1277
1480
|
}
|
|
1278
1481
|
|
|
1482
|
+
const promises = [];
|
|
1279
1483
|
for (let i = 0, len = validators.length; i < len; ++i) {
|
|
1280
|
-
if (err) {
|
|
1281
|
-
break;
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
1484
|
const v = validators[i];
|
|
1285
1485
|
const validator = v.validator;
|
|
1286
1486
|
let ok;
|
|
1287
1487
|
|
|
1288
|
-
const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) :
|
|
1289
|
-
validatorProperties.path = options
|
|
1488
|
+
const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : clone(v);
|
|
1489
|
+
validatorProperties.path = options?.path || path;
|
|
1290
1490
|
validatorProperties.fullPath = this.$fullPath;
|
|
1291
1491
|
validatorProperties.value = value;
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
validate(validator.test(value), validatorProperties, scope);
|
|
1295
|
-
continue;
|
|
1492
|
+
if (typeof value === 'string') {
|
|
1493
|
+
validatorProperties.length = value.length;
|
|
1296
1494
|
}
|
|
1297
1495
|
|
|
1298
|
-
if (
|
|
1496
|
+
if (value === undefined && validator !== this.requiredValidator) {
|
|
1299
1497
|
continue;
|
|
1300
1498
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1499
|
+
if (validator instanceof RegExp) {
|
|
1500
|
+
ok = validator.test(value);
|
|
1501
|
+
if (ok === false) {
|
|
1502
|
+
const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
|
|
1503
|
+
err = new ErrorConstructor(validatorProperties, scope);
|
|
1504
|
+
err[validatorErrorSymbol] = true;
|
|
1505
|
+
throw err;
|
|
1506
|
+
}
|
|
1507
|
+
continue;
|
|
1508
|
+
} else if (typeof validator !== 'function') {
|
|
1304
1509
|
continue;
|
|
1305
1510
|
}
|
|
1306
1511
|
|
|
@@ -1318,39 +1523,36 @@ SchemaType.prototype.doValidate = function(value, fn, scope, options) {
|
|
|
1318
1523
|
}
|
|
1319
1524
|
}
|
|
1320
1525
|
|
|
1321
|
-
if (
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
});
|
|
1344
|
-
}
|
|
1345
|
-
} else {
|
|
1526
|
+
if (typeof ok?.then === 'function') {
|
|
1527
|
+
promises.push(
|
|
1528
|
+
ok.then(
|
|
1529
|
+
function(ok) {
|
|
1530
|
+
if (ok === false) {
|
|
1531
|
+
const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
|
|
1532
|
+
err = new ErrorConstructor(validatorProperties, scope);
|
|
1533
|
+
err[validatorErrorSymbol] = true;
|
|
1534
|
+
throw err;
|
|
1535
|
+
}
|
|
1536
|
+
},
|
|
1537
|
+
function(error) {
|
|
1538
|
+
validatorProperties.reason = error;
|
|
1539
|
+
validatorProperties.message = error.message;
|
|
1540
|
+
ok = false;
|
|
1541
|
+
const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
|
|
1542
|
+
err = new ErrorConstructor(validatorProperties, scope);
|
|
1543
|
+
err[validatorErrorSymbol] = true;
|
|
1544
|
+
throw err;
|
|
1545
|
+
})
|
|
1546
|
+
);
|
|
1547
|
+
} else if (ok !== undefined && !ok) {
|
|
1346
1548
|
const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
|
|
1347
1549
|
err = new ErrorConstructor(validatorProperties, scope);
|
|
1348
1550
|
err[validatorErrorSymbol] = true;
|
|
1349
|
-
|
|
1350
|
-
fn(err);
|
|
1351
|
-
});
|
|
1551
|
+
throw err;
|
|
1352
1552
|
}
|
|
1353
1553
|
}
|
|
1554
|
+
|
|
1555
|
+
await Promise.all(promises);
|
|
1354
1556
|
};
|
|
1355
1557
|
|
|
1356
1558
|
|
|
@@ -1370,10 +1572,10 @@ function _validate(ok, validatorProperties) {
|
|
|
1370
1572
|
*
|
|
1371
1573
|
* This method ignores the asynchronous validators.
|
|
1372
1574
|
*
|
|
1373
|
-
* @param {
|
|
1374
|
-
* @param {
|
|
1375
|
-
* @param {
|
|
1376
|
-
* @param {
|
|
1575
|
+
* @param {any} value
|
|
1576
|
+
* @param {object} scope
|
|
1577
|
+
* @param {object} [options]
|
|
1578
|
+
* @param {string} [options.path]
|
|
1377
1579
|
* @return {MongooseError|null}
|
|
1378
1580
|
* @api private
|
|
1379
1581
|
*/
|
|
@@ -1399,7 +1601,6 @@ SchemaType.prototype.doValidateSync = function(value, scope, options) {
|
|
|
1399
1601
|
let i = 0;
|
|
1400
1602
|
const len = validators.length;
|
|
1401
1603
|
for (i = 0; i < len; ++i) {
|
|
1402
|
-
|
|
1403
1604
|
const v = validators[i];
|
|
1404
1605
|
|
|
1405
1606
|
if (v === null || typeof v !== 'object') {
|
|
@@ -1407,10 +1608,13 @@ SchemaType.prototype.doValidateSync = function(value, scope, options) {
|
|
|
1407
1608
|
}
|
|
1408
1609
|
|
|
1409
1610
|
const validator = v.validator;
|
|
1410
|
-
const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) :
|
|
1411
|
-
validatorProperties.path = options
|
|
1611
|
+
const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : clone(v);
|
|
1612
|
+
validatorProperties.path = options?.path || path;
|
|
1412
1613
|
validatorProperties.fullPath = this.$fullPath;
|
|
1413
1614
|
validatorProperties.value = value;
|
|
1615
|
+
if (typeof value === 'string') {
|
|
1616
|
+
validatorProperties.length = value.length;
|
|
1617
|
+
}
|
|
1414
1618
|
let ok = false;
|
|
1415
1619
|
|
|
1416
1620
|
// Skip any explicit async validators. Validators that return a promise
|
|
@@ -1441,7 +1645,7 @@ SchemaType.prototype.doValidateSync = function(value, scope, options) {
|
|
|
1441
1645
|
|
|
1442
1646
|
// Skip any validators that return a promise, we can't handle those
|
|
1443
1647
|
// synchronously
|
|
1444
|
-
if (
|
|
1648
|
+
if (typeof ok?.then === 'function') {
|
|
1445
1649
|
continue;
|
|
1446
1650
|
}
|
|
1447
1651
|
err = _validate(ok, validatorProperties);
|
|
@@ -1457,18 +1661,18 @@ SchemaType.prototype.doValidateSync = function(value, scope, options) {
|
|
|
1457
1661
|
* Determines if value is a valid Reference.
|
|
1458
1662
|
*
|
|
1459
1663
|
* @param {SchemaType} self
|
|
1460
|
-
* @param {
|
|
1664
|
+
* @param {object} value
|
|
1461
1665
|
* @param {Document} doc
|
|
1462
|
-
* @param {
|
|
1463
|
-
* @return {
|
|
1666
|
+
* @param {boolean} init
|
|
1667
|
+
* @return {boolean}
|
|
1464
1668
|
* @api private
|
|
1465
1669
|
*/
|
|
1466
1670
|
|
|
1467
1671
|
SchemaType._isRef = function(self, value, doc, init) {
|
|
1468
1672
|
// fast path
|
|
1469
|
-
let ref = init &&
|
|
1673
|
+
let ref = init && (self.options?.ref || self.options?.refPath);
|
|
1470
1674
|
|
|
1471
|
-
if (!ref && doc
|
|
1675
|
+
if (!ref && doc?.$__ != null) {
|
|
1472
1676
|
// checks for
|
|
1473
1677
|
// - this populated with adhoc model and no ref was set in schema OR
|
|
1474
1678
|
// - setting / pushing values after population
|
|
@@ -1499,13 +1703,13 @@ SchemaType._isRef = function(self, value, doc, init) {
|
|
|
1499
1703
|
* ignore
|
|
1500
1704
|
*/
|
|
1501
1705
|
|
|
1502
|
-
SchemaType.prototype._castRef = function _castRef(value, doc, init) {
|
|
1706
|
+
SchemaType.prototype._castRef = function _castRef(value, doc, init, options) {
|
|
1503
1707
|
if (value == null) {
|
|
1504
1708
|
return value;
|
|
1505
1709
|
}
|
|
1506
1710
|
|
|
1507
|
-
if (value
|
|
1508
|
-
value.$__.wasPopulated = value.$__.wasPopulated || { value: value._id };
|
|
1711
|
+
if (isMongooseDocument(value)) {
|
|
1712
|
+
value.$__.wasPopulated = value.$__.wasPopulated || { value: value._doc._id };
|
|
1509
1713
|
return value;
|
|
1510
1714
|
}
|
|
1511
1715
|
|
|
@@ -1530,8 +1734,9 @@ SchemaType.prototype._castRef = function _castRef(value, doc, init) {
|
|
|
1530
1734
|
!doc.$__.populated[path].options ||
|
|
1531
1735
|
!doc.$__.populated[path].options.options ||
|
|
1532
1736
|
!doc.$__.populated[path].options.options.lean) {
|
|
1533
|
-
|
|
1534
|
-
ret
|
|
1737
|
+
const PopulatedModel = pop ? pop.options[populateModelSymbol] : owner.constructor.db.model(this.options.ref);
|
|
1738
|
+
ret = PopulatedModel.hydrate(value, null, options);
|
|
1739
|
+
ret.$__.wasPopulated = { value: ret._doc._id, options: { [populateModelSymbol]: PopulatedModel } };
|
|
1535
1740
|
}
|
|
1536
1741
|
|
|
1537
1742
|
return ret;
|
|
@@ -1541,21 +1746,21 @@ SchemaType.prototype._castRef = function _castRef(value, doc, init) {
|
|
|
1541
1746
|
* ignore
|
|
1542
1747
|
*/
|
|
1543
1748
|
|
|
1544
|
-
function handleSingle(val) {
|
|
1545
|
-
return this.castForQuery(val);
|
|
1749
|
+
function handleSingle(val, context) {
|
|
1750
|
+
return this.castForQuery(null, val, context);
|
|
1546
1751
|
}
|
|
1547
1752
|
|
|
1548
1753
|
/*!
|
|
1549
1754
|
* ignore
|
|
1550
1755
|
*/
|
|
1551
1756
|
|
|
1552
|
-
function handleArray(val) {
|
|
1757
|
+
function handleArray(val, context) {
|
|
1553
1758
|
const _this = this;
|
|
1554
1759
|
if (!Array.isArray(val)) {
|
|
1555
|
-
return [this.castForQuery(val)];
|
|
1760
|
+
return [this.castForQuery(null, val, context)];
|
|
1556
1761
|
}
|
|
1557
1762
|
return val.map(function(m) {
|
|
1558
|
-
return _this.castForQuery(m);
|
|
1763
|
+
return _this.castForQuery(null, m, context);
|
|
1559
1764
|
});
|
|
1560
1765
|
}
|
|
1561
1766
|
|
|
@@ -1565,21 +1770,27 @@ function handleArray(val) {
|
|
|
1565
1770
|
* @api private
|
|
1566
1771
|
*/
|
|
1567
1772
|
|
|
1568
|
-
function handle$in(val) {
|
|
1773
|
+
function handle$in(val, context) {
|
|
1569
1774
|
const _this = this;
|
|
1570
1775
|
if (!Array.isArray(val)) {
|
|
1571
|
-
return [this.castForQuery(val)];
|
|
1776
|
+
return [this.castForQuery(null, val, context)];
|
|
1572
1777
|
}
|
|
1573
1778
|
return val.map(function(m) {
|
|
1574
1779
|
if (Array.isArray(m) && m.length === 0) {
|
|
1575
1780
|
return m;
|
|
1576
1781
|
}
|
|
1577
|
-
return _this.castForQuery(m);
|
|
1782
|
+
return _this.castForQuery(null, m, context);
|
|
1578
1783
|
});
|
|
1579
1784
|
}
|
|
1580
1785
|
|
|
1581
|
-
|
|
1582
|
-
*
|
|
1786
|
+
/**
|
|
1787
|
+
* Contains the handlers for different query operators for this schema type.
|
|
1788
|
+
* For example, `$conditionalHandlers.$exists` is the function Mongoose calls to cast `$exists` filter operators.
|
|
1789
|
+
*
|
|
1790
|
+
* @property $conditionalHandlers
|
|
1791
|
+
* @memberOf SchemaType
|
|
1792
|
+
* @instance
|
|
1793
|
+
* @api public
|
|
1583
1794
|
*/
|
|
1584
1795
|
|
|
1585
1796
|
SchemaType.prototype.$conditionalHandlers = {
|
|
@@ -1592,63 +1803,34 @@ SchemaType.prototype.$conditionalHandlers = {
|
|
|
1592
1803
|
$type: $type
|
|
1593
1804
|
};
|
|
1594
1805
|
|
|
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
1806
|
/**
|
|
1621
1807
|
* Cast the given value with the given optional query operator.
|
|
1622
1808
|
*
|
|
1623
|
-
* @param {
|
|
1624
|
-
* @param {
|
|
1625
|
-
* @
|
|
1809
|
+
* @param {string} [$conditional] query operator, like `$eq` or `$in`
|
|
1810
|
+
* @param {any} val
|
|
1811
|
+
* @param {Query} context
|
|
1812
|
+
* @return {any}
|
|
1626
1813
|
* @api private
|
|
1627
1814
|
*/
|
|
1628
1815
|
|
|
1629
|
-
SchemaType.prototype.castForQuery = function($conditional, val) {
|
|
1816
|
+
SchemaType.prototype.castForQuery = function($conditional, val, context) {
|
|
1630
1817
|
let handler;
|
|
1631
|
-
if (
|
|
1632
|
-
handler = this.$conditionalHandlers
|
|
1818
|
+
if ($conditional != null) {
|
|
1819
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
1633
1820
|
if (!handler) {
|
|
1634
|
-
throw new
|
|
1821
|
+
throw new MongooseError('Can\'t use ' + $conditional);
|
|
1635
1822
|
}
|
|
1636
|
-
return handler.call(this, val);
|
|
1823
|
+
return handler.call(this, val, context);
|
|
1637
1824
|
}
|
|
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
1825
|
|
|
1650
|
-
|
|
1651
|
-
|
|
1826
|
+
try {
|
|
1827
|
+
return this.applySetters(val, context);
|
|
1828
|
+
} catch (err) {
|
|
1829
|
+
if (err instanceof CastError && err.path === this.path && this.$fullPath != null) {
|
|
1830
|
+
err.path = this.$fullPath;
|
|
1831
|
+
}
|
|
1832
|
+
throw err;
|
|
1833
|
+
}
|
|
1652
1834
|
};
|
|
1653
1835
|
|
|
1654
1836
|
/**
|
|
@@ -1680,8 +1862,8 @@ SchemaType.checkRequired = function(fn) {
|
|
|
1680
1862
|
/**
|
|
1681
1863
|
* Default check for if this path satisfies the `required` validator.
|
|
1682
1864
|
*
|
|
1683
|
-
* @param {
|
|
1684
|
-
* @return {
|
|
1865
|
+
* @param {any} val
|
|
1866
|
+
* @return {boolean} `true` when the value is not `null`, `false` otherwise
|
|
1685
1867
|
* @api private
|
|
1686
1868
|
*/
|
|
1687
1869
|
|
|
@@ -1698,9 +1880,15 @@ SchemaType.prototype.checkRequired = function(val) {
|
|
|
1698
1880
|
|
|
1699
1881
|
SchemaType.prototype.clone = function() {
|
|
1700
1882
|
const options = Object.assign({}, this.options);
|
|
1701
|
-
const schematype = new this.constructor(this.path, options, this.instance);
|
|
1883
|
+
const schematype = new this.constructor(this.path, options, this.instance, this.parentSchema);
|
|
1702
1884
|
schematype.validators = this.validators.slice();
|
|
1703
1885
|
if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator;
|
|
1886
|
+
if (this.allowNullValidator !== undefined) schematype.allowNullValidator = this.allowNullValidator;
|
|
1887
|
+
if (this.enumValidator !== undefined) schematype.enumValidator = this.enumValidator;
|
|
1888
|
+
if (this.minValidator !== undefined) schematype.minValidator = this.minValidator;
|
|
1889
|
+
if (this.maxValidator !== undefined) schematype.maxValidator = this.maxValidator;
|
|
1890
|
+
if (this.minlengthValidator !== undefined) schematype.minlengthValidator = this.minlengthValidator;
|
|
1891
|
+
if (this.maxlengthValidator !== undefined) schematype.maxlengthValidator = this.maxlengthValidator;
|
|
1704
1892
|
if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue;
|
|
1705
1893
|
if (this.$immutable !== undefined && this.options.immutable === undefined) {
|
|
1706
1894
|
schematype.$immutable = this.$immutable;
|
|
@@ -1716,6 +1904,53 @@ SchemaType.prototype.clone = function() {
|
|
|
1716
1904
|
return schematype;
|
|
1717
1905
|
};
|
|
1718
1906
|
|
|
1907
|
+
/**
|
|
1908
|
+
* Returns the embedded schema type, if any. For arrays, document arrays, and maps, `getEmbeddedSchemaType()`
|
|
1909
|
+
* returns the schema type of the array's elements (or map's elements). For other types, `getEmbeddedSchemaType()`
|
|
1910
|
+
* returns `undefined`.
|
|
1911
|
+
*
|
|
1912
|
+
* #### Example:
|
|
1913
|
+
*
|
|
1914
|
+
* const schema = new Schema({ name: String, tags: [String] });
|
|
1915
|
+
* schema.path('name').getEmbeddedSchemaType(); // undefined
|
|
1916
|
+
* schema.path('tags').getEmbeddedSchemaType(); // SchemaString { path: 'tags', ... }
|
|
1917
|
+
*
|
|
1918
|
+
* @returns {SchemaType} embedded schematype
|
|
1919
|
+
* @api public
|
|
1920
|
+
*/
|
|
1921
|
+
|
|
1922
|
+
SchemaType.prototype.getEmbeddedSchemaType = function getEmbeddedSchemaType() {
|
|
1923
|
+
return this.embeddedSchemaType;
|
|
1924
|
+
};
|
|
1925
|
+
|
|
1926
|
+
/*!
|
|
1927
|
+
* If _duplicateKeyErrorMessage is a string, replace unique index errors "E11000 duplicate key error" with this string.
|
|
1928
|
+
*
|
|
1929
|
+
* @api private
|
|
1930
|
+
*/
|
|
1931
|
+
|
|
1932
|
+
SchemaType.prototype._duplicateKeyErrorMessage = null;
|
|
1933
|
+
|
|
1934
|
+
/**
|
|
1935
|
+
* Returns this schema type's representation in a JSON schema.
|
|
1936
|
+
*
|
|
1937
|
+
* @param {object} [options]
|
|
1938
|
+
* @param {boolean} [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
|
|
1939
|
+
* @returns {object} JSON schema properties
|
|
1940
|
+
*/
|
|
1941
|
+
|
|
1942
|
+
SchemaType.prototype.toJSONSchema = function toJSONSchema(_options) { // eslint-disable-line no-unused-vars
|
|
1943
|
+
throw new MongooseError(`Converting unsupported SchemaType to JSON Schema: ${this.instance} at path "${this.path}"`);
|
|
1944
|
+
};
|
|
1945
|
+
|
|
1946
|
+
/**
|
|
1947
|
+
* Returns the BSON type that the schema corresponds to, for automatic encryption.
|
|
1948
|
+
* @api private
|
|
1949
|
+
*/
|
|
1950
|
+
SchemaType.prototype.autoEncryptionType = function autoEncryptionType() {
|
|
1951
|
+
return null;
|
|
1952
|
+
};
|
|
1953
|
+
|
|
1719
1954
|
/*!
|
|
1720
1955
|
* Module exports.
|
|
1721
1956
|
*/
|