forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schematype.js
1689 lines (1502 loc) · 48.5 KB
/
schematype.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/*!
* Module dependencies.
*/
const MongooseError = require('./error/index');
const SchemaTypeOptions = require('./options/SchemaTypeOptions');
const $exists = require('./schema/operators/exists');
const $type = require('./schema/operators/type');
const clone = require('./helpers/clone');
const handleImmutable = require('./helpers/schematype/handleImmutable');
const isAsyncFunction = require('./helpers/isAsyncFunction');
const isSimpleValidator = require('./helpers/isSimpleValidator');
const immediate = require('./helpers/immediate');
const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
const utils = require('./utils');
const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol;
const documentIsModified = require('./helpers/symbols').documentIsModified;
const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
const CastError = MongooseError.CastError;
const ValidatorError = MongooseError.ValidatorError;
const setOptionsForDefaults = { _skipMarkModified: true };
/**
* SchemaType constructor. Do **not** instantiate `SchemaType` directly.
* Mongoose converts your schema paths into SchemaTypes automatically.
*
* #### Example:
*
* const schema = new Schema({ name: String });
* schema.path('name') instanceof SchemaType; // true
*
* @param {String} path
* @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html)
* @param {String} [instance]
* @api public
*/
function SchemaType(path, options, instance) {
this[schemaTypeSymbol] = true;
this.path = path;
this.instance = instance;
this.validators = [];
this.getters = this.constructor.hasOwnProperty('getters') ?
this.constructor.getters.slice() :
[];
this.setters = [];
this.splitPath();
options = options || {};
const defaultOptions = this.constructor.defaultOptions || {};
const defaultOptionsKeys = Object.keys(defaultOptions);
for (const option of defaultOptionsKeys) {
if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
options[option] = defaultOptions[option];
}
}
if (options.select == null) {
delete options.select;
}
const Options = this.OptionsConstructor || SchemaTypeOptions;
this.options = new Options(options);
this._index = null;
if (utils.hasUserDefinedProperty(this.options, 'immutable')) {
this.$immutable = this.options.immutable;
handleImmutable(this);
}
const keys = Object.keys(this.options);
for (const prop of keys) {
if (prop === 'cast') {
this.castFunction(this.options[prop]);
continue;
}
if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') {
// { unique: true, index: true }
if (prop === 'index' && this._index) {
if (options.index === false) {
const index = this._index;
if (typeof index === 'object' && index != null) {
if (index.unique) {
throw new Error('Path "' + this.path + '" may not have `index` ' +
'set to false and `unique` set to true');
}
if (index.sparse) {
throw new Error('Path "' + this.path + '" may not have `index` ' +
'set to false and `sparse` set to true');
}
}
this._index = false;
}
continue;
}
const val = options[prop];
// Special case so we don't screw up array defaults, see gh-5780
if (prop === 'default') {
this.default(val);
continue;
}
const opts = Array.isArray(val) ? val : [val];
this[prop].apply(this, opts);
}
}
Object.defineProperty(this, '$$context', {
enumerable: false,
configurable: false,
writable: true,
value: null
});
}
/**
* The class that Mongoose uses internally to instantiate this SchemaType's `options` property.
* @memberOf SchemaType
* @instance
* @api private
*/
SchemaType.prototype.OptionsConstructor = SchemaTypeOptions;
/**
* The path to this SchemaType in a Schema.
*
* #### Example:
*
* const schema = new Schema({ name: String });
* schema.path('name').path; // 'name'
*
* @property path
* @api public
* @memberOf SchemaType
*/
SchemaType.prototype.path;
/**
* The validators that Mongoose should run to validate properties at this SchemaType's path.
*
* #### Example:
*
* const schema = new Schema({ name: { type: String, required: true } });
* schema.path('name').validators.length; // 1, the `required` validator
*
* @property validators
* @api public
* @memberOf SchemaType
*/
SchemaType.prototype.validators;
/**
* True if this SchemaType has a required validator. False otherwise.
*
* #### Example:
*
* const schema = new Schema({ name: { type: String, required: true } });
* schema.path('name').isRequired; // true
*
* schema.path('name').required(false);
* schema.path('name').isRequired; // false
*
* @property isRequired
* @api public
* @memberOf SchemaType
*/
SchemaType.prototype.isRequired;
/**
* Split the current dottet path into segments
*
* @return {String[]|undefined}
* @api private
*/
SchemaType.prototype.splitPath = function() {
if (this._presplitPath != null) {
return this._presplitPath;
}
if (this.path == null) {
return undefined;
}
this._presplitPath = this.path.indexOf('.') === -1 ? [this.path] : this.path.split('.');
return this._presplitPath;
};
/**
* Get/set the function used to cast arbitrary values to this type.
*
* #### Example:
*
* // Disallow `null` for numbers, and don't try to cast any values to
* // numbers, so even strings like '123' will cause a CastError.
* mongoose.Number.cast(function(v) {
* assert.ok(v === undefined || typeof v === 'number');
* return v;
* });
*
* @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed
* @return {Function}
* @static
* @memberOf SchemaType
* @function cast
* @api public
*/
SchemaType.cast = function cast(caster) {
if (arguments.length === 0) {
return this._cast;
}
if (caster === false) {
caster = v => v;
}
this._cast = caster;
return this._cast;
};
/**
* Get/set the function used to cast arbitrary values to this particular schematype instance.
* Overrides `SchemaType.cast()`.
*
* #### Example:
*
* // Disallow `null` for numbers, and don't try to cast any values to
* // numbers, so even strings like '123' will cause a CastError.
* const number = new mongoose.Number('mypath', {});
* number.cast(function(v) {
* assert.ok(v === undefined || typeof v === 'number');
* return v;
* });
*
* @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed
* @return {Function}
* @memberOf SchemaType
* @api public
*/
SchemaType.prototype.castFunction = function castFunction(caster) {
if (arguments.length === 0) {
return this._castFunction;
}
if (caster === false) {
caster = this.constructor._defaultCaster || (v => v);
}
this._castFunction = caster;
return this._castFunction;
};
/**
* The function that Mongoose calls to cast arbitrary values to this SchemaType.
*
* @param {Object} value value to cast
* @param {Document} doc document that triggers the casting
* @param {Boolean} init
* @api public
*/
SchemaType.prototype.cast = function cast() {
throw new Error('Base SchemaType class does not implement a `cast()` function');
};
/**
* Sets a default option for this schema type.
*
* #### Example:
*
* // Make all strings be trimmed by default
* mongoose.SchemaTypes.String.set('trim', true);
*
* @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...)
* @param {Any} value The value of the option you'd like to set.
* @return {void}
* @static
* @memberOf SchemaType
* @function set
* @api public
*/
SchemaType.set = function set(option, value) {
if (!this.hasOwnProperty('defaultOptions')) {
this.defaultOptions = Object.assign({}, this.defaultOptions);
}
this.defaultOptions[option] = value;
};
/**
* Attaches a getter for all instances of this schema type.
*
* #### Example:
*
* // Make all numbers round down
* mongoose.Number.get(function(v) { return Math.floor(v); });
*
* @param {Function} getter
* @return {this}
* @static
* @memberOf SchemaType
* @function get
* @api public
*/
SchemaType.get = function(getter) {
this.getters = this.hasOwnProperty('getters') ? this.getters : [];
this.getters.push(getter);
};
/**
* Sets a default value for this SchemaType.
*
* #### Example:
*
* const schema = new Schema({ n: { type: Number, default: 10 })
* const M = db.model('M', schema)
* const m = new M;
* console.log(m.n) // 10
*
* 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.
*
* #### Example:
*
* // values are cast:
* const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
* const M = db.model('M', schema)
* const m = new M;
* console.log(m.aNumber) // 4.815162342
*
* // default unique objects for Mixed types:
* const schema = new Schema({ mixed: Schema.Types.Mixed });
* schema.path('mixed').default(function () {
* return {};
* });
*
* // if we don't use a function to return object literals for Mixed defaults,
* // each document will receive a reference to the same object literal creating
* // a "shared" object instance:
* const schema = new Schema({ mixed: Schema.Types.Mixed });
* schema.path('mixed').default({});
* const M = db.model('M', schema);
* const m1 = new M;
* m1.mixed.added = 1;
* console.log(m1.mixed); // { added: 1 }
* const m2 = new M;
* console.log(m2.mixed); // { added: 1 }
*
* @param {Function|any} val The default value to set
* @return {Any|undefined} Returns the set default value.
* @api public
*/
SchemaType.prototype.default = function(val) {
if (arguments.length === 1) {
if (val === void 0) {
this.defaultValue = void 0;
return void 0;
}
if (val != null && val.instanceOfSchema) {
throw new MongooseError('Cannot set default value of path `' + this.path +
'` to a mongoose Schema instance.');
}
this.defaultValue = val;
return this.defaultValue;
} else if (arguments.length > 1) {
this.defaultValue = [...arguments];
}
return this.defaultValue;
};
/**
* Declares the index options for this schematype.
*
* #### Example:
*
* const s = new Schema({ name: { type: String, index: true })
* const s = new Schema({ name: { type: String, index: -1 })
* const s = new Schema({ loc: { type: [Number], index: 'hashed' })
* const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
* const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
* const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
* s.path('my.path').index(true);
* s.path('my.date').index({ expires: 60 });
* s.path('my.path').index({ unique: true, sparse: true });
*
* #### Note:
*
* _Indexes are created [in the background](https://www.mongodb.com/docs/manual/core/index-creation/#index-creation-background)
* by default. If `background` is set to `false`, MongoDB will not execute any
* read/write operations you send until the index build.
* Specify `background: false` to override Mongoose's default._
*
* @param {Object|Boolean|String|Number} options
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.index = function(options) {
this._index = options;
utils.expires(this._index);
return this;
};
/**
* Declares an unique index.
*
* #### Example:
*
* const s = new Schema({ name: { type: String, unique: true } });
* s.path('name').index({ unique: true });
*
* _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
*
* @param {Boolean} bool
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.unique = function(bool) {
if (this._index === false) {
if (!bool) {
return;
}
throw new Error('Path "' + this.path + '" may not have `index` set to ' +
'false and `unique` set to true');
}
if (!this.options.hasOwnProperty('index') && bool === false) {
return this;
}
if (this._index == null || this._index === true) {
this._index = {};
} else if (typeof this._index === 'string') {
this._index = { type: this._index };
}
this._index.unique = bool;
return this;
};
/**
* Declares a full text index.
*
* ### Example:
*
* const s = new Schema({ name : { type: String, text : true } })
* s.path('name').index({ text : true });
*
* @param {Boolean} bool
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.text = function(bool) {
if (this._index === false) {
if (!bool) {
return this;
}
throw new Error('Path "' + this.path + '" may not have `index` set to ' +
'false and `text` set to true');
}
if (!this.options.hasOwnProperty('index') && bool === false) {
return this;
}
if (this._index === null || this._index === undefined ||
typeof this._index === 'boolean') {
this._index = {};
} else if (typeof this._index === 'string') {
this._index = { type: this._index };
}
this._index.text = bool;
return this;
};
/**
* Declares a sparse index.
*
* #### Example:
*
* const s = new Schema({ name: { type: String, sparse: true } });
* s.path('name').index({ sparse: true });
*
* @param {Boolean} bool
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.sparse = function(bool) {
if (this._index === false) {
if (!bool) {
return this;
}
throw new Error('Path "' + this.path + '" may not have `index` set to ' +
'false and `sparse` set to true');
}
if (!this.options.hasOwnProperty('index') && bool === false) {
return this;
}
if (this._index == null || typeof this._index === 'boolean') {
this._index = {};
} else if (typeof this._index === 'string') {
this._index = { type: this._index };
}
this._index.sparse = bool;
return this;
};
/**
* Defines this path as immutable. Mongoose prevents you from changing
* immutable paths unless the parent document has [`isNew: true`](/docs/api/document.html#document_Document-isNew).
*
* #### Example:
*
* const schema = new Schema({
* name: { type: String, immutable: true },
* age: Number
* });
* const Model = mongoose.model('Test', schema);
*
* await Model.create({ name: 'test' });
* const doc = await Model.findOne();
*
* doc.isNew; // false
* doc.name = 'new name';
* doc.name; // 'test', because `name` is immutable
*
* Mongoose also prevents changing immutable properties using `updateOne()`
* and `updateMany()` based on [strict mode](/docs/guide.html#strict).
*
* #### Example:
*
* // Mongoose will strip out the `name` update, because `name` is immutable
* Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
*
* // If `strict` is set to 'throw', Mongoose will throw an error if you
* // update `name`
* const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
* then(() => null, err => err);
* err.name; // StrictModeError
*
* // If `strict` is `false`, Mongoose allows updating `name` even though
* // the property is immutable.
* Model.updateOne({}, { name: 'test2' }, { strict: false });
*
* @param {Boolean} bool
* @return {SchemaType} this
* @see isNew /docs/api/document.html#document_Document-isNew
* @api public
*/
SchemaType.prototype.immutable = function(bool) {
this.$immutable = bool;
handleImmutable(this);
return this;
};
/**
* Defines a custom function for transforming this path when converting a document to JSON.
*
* Mongoose calls this function with one parameter: the current `value` of the path. Mongoose
* then uses the return value in the JSON output.
*
* #### Example:
*
* const schema = new Schema({
* date: { type: Date, transform: v => v.getFullYear() }
* });
* const Model = mongoose.model('Test', schema);
*
* await Model.create({ date: new Date('2016-06-01') });
* const doc = await Model.findOne();
*
* doc.date instanceof Date; // true
*
* doc.toJSON().date; // 2016 as a number
* JSON.stringify(doc); // '{"_id":...,"date":2016}'
*
* @param {Function} fn
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.transform = function(fn) {
this.options.transform = fn;
return this;
};
/**
* Adds a setter to this schematype.
*
* #### Example:
*
* function capitalize (val) {
* if (typeof val !== 'string') val = '';
* return val.charAt(0).toUpperCase() + val.substring(1);
* }
*
* // defining within the schema
* const s = new Schema({ name: { type: String, set: capitalize }});
*
* // or with the SchemaType
* const s = new Schema({ name: String })
* s.path('name').set(capitalize);
*
* Setters allow you to transform the data before it gets to the raw mongodb
* document or query.
*
* Suppose you are implementing user registration for a website. Users provide
* an email and password, which gets saved to mongodb. The email is a string
* that you will want to normalize to lower case, in order to avoid one email
* having more than one account -- e.g., otherwise, [email protected] can be registered for 2 accounts via [email protected] and [email protected].
*
* You can set up email lower case normalization easily via a Mongoose setter.
*
* function toLower(v) {
* return v.toLowerCase();
* }
*
* const UserSchema = new Schema({
* email: { type: String, set: toLower }
* });
*
* const User = db.model('User', UserSchema);
*
* const user = new User({email: '[email protected]'});
* console.log(user.email); // '[email protected]'
*
* // or
* const user = new User();
* user.email = '[email protected]';
* console.log(user.email); // '[email protected]'
* User.updateOne({ _id: _id }, { $set: { email: '[email protected]' } }); // update to '[email protected]'
*
* As you can see above, setters allow you to transform the data before it
* stored in MongoDB, or before executing a query.
*
* _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._
*
* new Schema({ email: { type: String, lowercase: true }})
*
* 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.
*
* function inspector (val, priorValue, schematype) {
* if (schematype.options.required) {
* return schematype.path + ' is required';
* } else {
* return val;
* }
* }
*
* const VirusSchema = new Schema({
* name: { type: String, required: true, set: inspector },
* taxonomy: { type: String, set: inspector }
* })
*
* const Virus = db.model('Virus', VirusSchema);
* const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
*
* console.log(v.name); // name is required
* console.log(v.taxonomy); // Parvovirinae
*
* You can also use setters to modify other properties on the document. If
* you're setting a property `name` on a document, the setter will run with
* `this` as the document. Be careful, in mongoose 5 setters will also run
* when querying by `name` with `this` as the query.
*
* const nameSchema = new Schema({ name: String, keywords: [String] });
* nameSchema.path('name').set(function(v) {
* // Need to check if `this` is a document, because in mongoose 5
* // setters will also run on queries, in which case `this` will be a
* // mongoose query object.
* if (this instanceof Document && v != null) {
* this.keywords = v.split(' ');
* }
* return v;
* });
*
* @param {Function} fn
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.set = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError('A setter must be a function.');
}
this.setters.push(fn);
return this;
};
/**
* Adds a getter to this schematype.
*
* #### Example:
*
* function dob (val) {
* if (!val) return val;
* return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
* }
*
* // defining within the schema
* const s = new Schema({ born: { type: Date, get: dob })
*
* // or by retreiving its SchemaType
* const s = new Schema({ born: Date })
* s.path('born').get(dob)
*
* Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.
*
* 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:
*
* function obfuscate (cc) {
* return '****-****-****-' + cc.slice(cc.length-4, cc.length);
* }
*
* const AccountSchema = new Schema({
* creditCardNumber: { type: String, get: obfuscate }
* });
*
* const Account = db.model('Account', AccountSchema);
*
* Account.findById(id, function (err, found) {
* console.log(found.creditCardNumber); // '****-****-****-1234'
* });
*
* 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.
*
* function inspector (val, priorValue, schematype) {
* if (schematype.options.required) {
* return schematype.path + ' is required';
* } else {
* return schematype.path + ' is not';
* }
* }
*
* const VirusSchema = new Schema({
* name: { type: String, required: true, get: inspector },
* taxonomy: { type: String, get: inspector }
* })
*
* const Virus = db.model('Virus', VirusSchema);
*
* Virus.findById(id, function (err, virus) {
* console.log(virus.name); // name is required
* console.log(virus.taxonomy); // taxonomy is not
* })
*
* @param {Function} fn
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.get = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError('A getter must be a function.');
}
this.getters.push(fn);
return this;
};
/**
* Adds validator(s) for this document path.
*
* Validators always receive the value to validate as their first argument and
* must return `Boolean`. Returning `false` or throwing an error means
* validation failed.
*
* The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used.
*
* #### Example:
*
* // make sure every value is equal to "something"
* function validator (val) {
* return val === 'something';
* }
* new Schema({ name: { type: String, validate: validator }});
*
* // with a custom error message
*
* const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
* new Schema({ name: { type: String, validate: custom }});
*
* // adding many validators at a time
*
* const many = [
* { validator: validator, msg: 'uh oh' }
* , { validator: anotherValidator, msg: 'failed' }
* ]
* new Schema({ name: { type: String, validate: many }});
*
* // or utilizing SchemaType methods directly:
*
* const schema = new Schema({ name: 'string' });
* schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');
*
* #### Error message templates:
*
* From the examples above, you may have noticed that error messages support
* basic templating. There are a few other template keywords besides `{PATH}`
* and `{VALUE}` too. To find out more, details are available
* [here](#error_messages_MongooseError-messages).
*
* If Mongoose's built-in error message templating isn't enough, Mongoose
* supports setting the `message` property to a function.
*
* schema.path('name').validate({
* validator: function(v) { return v.length > 5; },
* // `errors['name']` will be "name must have length 5, got 'foo'"
* message: function(props) {
* return `${props.path} must have length 5, got '${props.value}'`;
* }
* });
*
* To bypass Mongoose's error messages and just copy the error message that
* the validator throws, do this:
*
* schema.path('name').validate({
* validator: function() { throw new Error('Oops!'); },
* // `errors['name']` will be "Oops!"
* message: function(props) { return props.reason.message; }
* });
*
* #### Asynchronous validation:
*
* Mongoose supports validators that return a promise. A validator that returns
* a promise is called an _async validator_. Async validators run in
* parallel, and `validate()` will wait until all async validators have settled.
*
* schema.path('name').validate({
* validator: function (value) {
* return new Promise(function (resolve, reject) {
* resolve(false); // validation failed
* });
* }
* });
*
* You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.
*
* Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate).
*
* 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.
*
* const conn = mongoose.createConnection(..);
* conn.on('error', handleError);
*
* const Product = conn.model('Product', yourSchema);
* const dvd = new Product(..);
* dvd.save(); // emits error on the `conn` above
*
* If you want to handle these errors at the Model level, add an `error`
* listener to your Model as shown below.
*
* // registering an error listener on the Model lets us handle errors more locally
* Product.on('error', handleError);
*
* @param {RegExp|Function|Object} obj validator function, or hash describing options
* @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.
* @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string
* @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.
* @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string
* @param {String} [type] optional validator type
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.validate = function(obj, message, type) {
if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') {
let properties;
if (typeof message === 'function') {
properties = { validator: obj, message: message };
properties.type = type || 'user defined';
} else if (message instanceof Object && !type) {
properties = isSimpleValidator(message) ? Object.assign({}, message) : clone(message);
if (!properties.message) {
properties.message = properties.msg;
}
properties.validator = obj;
properties.type = properties.type || 'user defined';
} else {
if (message == null) {
message = MongooseError.messages.general.default;
}
if (!type) {
type = 'user defined';
}
properties = { message: message, type: type, validator: obj };
}
this.validators.push(properties);
return this;
}
let i;
let length;
let arg;
for (i = 0, length = arguments.length; i < length; i++) {
arg = arguments[i];
if (!utils.isPOJO(arg)) {
const msg = 'Invalid validator. Received (' + typeof arg + ') '
+ arg
+ '. See https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-validate';
throw new Error(msg);
}
this.validate(arg.validator, arg);
}
return this;
};
/**
* Adds a required validator to this SchemaType. The validator gets added
* to the front of this SchemaType's validators array using `unshift()`.
*
* #### Example:
*
* const s = new Schema({ born: { type: Date, required: true })
*
* // or with custom error message
*
* const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
*
* // or with a function
*
* const s = new Schema({
* userId: ObjectId,
* username: {
* type: String,
* required: function() { return this.userId != null; }
* }
* })
*
* // or with a function and a custom message
* const s = new Schema({
* userId: ObjectId,
* username: {
* type: String,
* required: [
* function() { return this.userId != null; },
* 'username is required if id is specified'
* ]
* }
* })
*
* // or through the path API
*
* s.path('name').required(true);
*
* // with custom error messaging
*
* s.path('name').required(true, 'grrr :( ');
*
* // or make a path conditionally required based on a function
* const isOver18 = function() { return this.age >= 18; };
* s.path('voterRegistrationId').required(isOver18);
*
* The required validator uses the SchemaType's `checkRequired` function to
* determine whether a given value satisfies the required validator. By default,
* a value satisfies the required validator if `val != null` (that is, if
* the value is not null nor undefined). However, most built-in mongoose schema
* types override the default `checkRequired` function:
*
* @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object
* @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean
* @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @see SchemaArray#checkRequired #schema_array_SchemaArray-checkRequired
* @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired
* @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer-schemaName
* @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min