-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathschema.js
2804 lines (2502 loc) · 86.2 KB
/
schema.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 EventEmitter = require('events').EventEmitter;
const Kareem = require('kareem');
const MongooseError = require('./error/mongooseError');
const SchemaType = require('./schemaType');
const SchemaTypeOptions = require('./options/schemaTypeOptions');
const VirtualOptions = require('./options/virtualOptions');
const VirtualType = require('./virtualType');
const addAutoId = require('./helpers/schema/addAutoId');
const clone = require('./helpers/clone');
const get = require('./helpers/get');
const getConstructorName = require('./helpers/getConstructorName');
const getIndexes = require('./helpers/schema/getIndexes');
const handleReadPreferenceAliases = require('./helpers/query/handleReadPreferenceAliases');
const idGetter = require('./helpers/schema/idGetter');
const merge = require('./helpers/schema/merge');
const mpath = require('mpath');
const setPopulatedVirtualValue = require('./helpers/populate/setPopulatedVirtualValue');
const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
const utils = require('./utils');
const validateRef = require('./helpers/populate/validateRef');
const util = require('util');
const hasNumericSubpathRegex = /\.\d+(\.|$)/;
let MongooseTypes;
const queryHooks = require('./constants').queryMiddlewareFunctions;
const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
const hookNames = queryHooks.concat(documentHooks).
reduce((s, hook) => s.add(hook), new Set());
const isPOJO = utils.isPOJO;
let id = 0;
const numberRE = /^\d+$/;
/**
* Schema constructor.
*
* #### Example:
*
* const child = new Schema({ name: String });
* const schema = new Schema({ name: String, age: Number, children: [child] });
* const Tree = mongoose.model('Tree', schema);
*
* // setting schema options
* new Schema({ name: String }, { id: false, autoIndex: false })
*
* #### Options:
*
* - [autoIndex](https://mongoosejs.com/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
* - [autoCreate](https://mongoosejs.com/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
* - [bufferCommands](https://mongoosejs.com/docs/guide.html#bufferCommands): bool - defaults to true
* - [bufferTimeoutMS](https://mongoosejs.com/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
* - [capped](https://mongoosejs.com/docs/guide.html#capped): bool | number | object - defaults to false
* - [collection](https://mongoosejs.com/docs/guide.html#collection): string - no default
* - [discriminatorKey](https://mongoosejs.com/docs/guide.html#discriminatorKey): string - defaults to `__t`
* - [id](https://mongoosejs.com/docs/guide.html#id): bool - defaults to true
* - [_id](https://mongoosejs.com/docs/guide.html#_id): bool - defaults to true
* - [minimize](https://mongoosejs.com/docs/guide.html#minimize): bool - controls [document#toObject](https://mongoosejs.com/docs/api/document.html#Document.prototype.toObject()) behavior when called manually - defaults to true
* - [read](https://mongoosejs.com/docs/guide.html#read): string
* - [writeConcern](https://mongoosejs.com/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://www.mongodb.com/docs/manual/reference/write-concern/)
* - [shardKey](https://mongoosejs.com/docs/guide.html#shardKey): object - defaults to `null`
* - [strict](https://mongoosejs.com/docs/guide.html#strict): bool - defaults to true
* - [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery): bool - defaults to false
* - [toJSON](https://mongoosejs.com/docs/guide.html#toJSON) - object - no default
* - [toObject](https://mongoosejs.com/docs/guide.html#toObject) - object - no default
* - [typeKey](https://mongoosejs.com/docs/guide.html#typeKey) - string - defaults to 'type'
* - [validateBeforeSave](https://mongoosejs.com/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
* - [validateModifiedOnly](https://mongoosejs.com/docs/api/document.html#Document.prototype.validate()) - bool - defaults to `false`
* - [versionKey](https://mongoosejs.com/docs/guide.html#versionKey): string or object - defaults to "__v"
* - [optimisticConcurrency](https://mongoosejs.com/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html).
* - [collation](https://mongoosejs.com/docs/guide.html#collation): object - defaults to null (which means use no collation)
* - [timeseries](https://mongoosejs.com/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection)
* - [selectPopulatedPaths](https://mongoosejs.com/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
* - [skipVersioning](https://mongoosejs.com/docs/guide.html#skipVersioning): object - paths to exclude from versioning
* - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
* - [pluginTags](https://mongoosejs.com/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag.
* - [virtuals](https://mongoosejs.com/docs/tutorials/virtuals.html#virtuals-via-schema-options): object - virtuals to define, alias for [`.virtual`](https://mongoosejs.com/docs/api/schema.html#Schema.prototype.virtual())
* - [collectionOptions]: object with options passed to [`createCollection()`](https://www.mongodb.com/docs/manual/reference/method/db.createCollection/) when calling `Model.createCollection()` or `autoCreate` set to true.
*
* #### Options for Nested Schemas:
*
* - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths.
*
* #### Note:
*
* _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
*
* @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
* @param {Object} [options]
* @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
* @event `init`: Emitted after the schema is compiled into a `Model`.
* @api public
*/
function Schema(obj, options) {
if (!(this instanceof Schema)) {
return new Schema(obj, options);
}
this.obj = obj;
this.paths = {};
this.aliases = {};
this.subpaths = {};
this.virtuals = {};
this.singleNestedPaths = {};
this.nested = {};
this.inherits = {};
this.callQueue = [];
this._indexes = [];
this._searchIndexes = [];
this.methods = (options && options.methods) || {};
this.methodOptions = {};
this.statics = (options && options.statics) || {};
this.tree = {};
this.query = (options && options.query) || {};
this.childSchemas = [];
this.plugins = [];
// For internal debugging. Do not use this to try to save a schema in MDB.
this.$id = ++id;
this.mapPaths = [];
this.s = {
hooks: new Kareem()
};
this.options = this.defaultOptions(options);
// build paths
if (Array.isArray(obj)) {
for (const definition of obj) {
this.add(definition);
}
} else if (obj) {
this.add(obj);
}
// build virtual paths
if (options && options.virtuals) {
const virtuals = options.virtuals;
const pathNames = Object.keys(virtuals);
for (const pathName of pathNames) {
const pathOptions = virtuals[pathName].options ? virtuals[pathName].options : undefined;
const virtual = this.virtual(pathName, pathOptions);
if (virtuals[pathName].get) {
virtual.get(virtuals[pathName].get);
}
if (virtuals[pathName].set) {
virtual.set(virtuals[pathName].set);
}
}
}
// check if _id's value is a subdocument (gh-2276)
const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
// ensure the documents get an auto _id unless disabled
const auto_id = !this.paths['_id'] &&
(this.options._id) && !_idSubDoc;
if (auto_id) {
addAutoId(this);
}
this.setupTimestamp(this.options.timestamps);
}
/**
* Create virtual properties with alias field
* @api private
*/
function aliasFields(schema, paths) {
for (const path of Object.keys(paths)) {
let alias = null;
if (paths[path] != null) {
alias = paths[path];
} else {
const options = get(schema.paths[path], 'options');
if (options == null) {
continue;
}
alias = options.alias;
}
if (!alias) {
continue;
}
const prop = schema.paths[path].path;
if (Array.isArray(alias)) {
for (const a of alias) {
if (typeof a !== 'string') {
throw new Error('Invalid value for alias option on ' + prop + ', got ' + a);
}
schema.aliases[a] = prop;
schema.
virtual(a).
get((function(p) {
return function() {
if (typeof this.get === 'function') {
return this.get(p);
}
return this[p];
};
})(prop)).
set((function(p) {
return function(v) {
return this.$set(p, v);
};
})(prop));
}
continue;
}
if (typeof alias !== 'string') {
throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
}
schema.aliases[alias] = prop;
schema.
virtual(alias).
get((function(p) {
return function() {
if (typeof this.get === 'function') {
return this.get(p);
}
return this[p];
};
})(prop)).
set((function(p) {
return function(v) {
return this.$set(p, v);
};
})(prop));
}
}
/*!
* Inherit from EventEmitter.
*/
Schema.prototype = Object.create(EventEmitter.prototype);
Schema.prototype.constructor = Schema;
Schema.prototype.instanceOfSchema = true;
/*!
* ignore
*/
Object.defineProperty(Schema.prototype, '$schemaType', {
configurable: false,
enumerable: false,
writable: true
});
/**
* Array of child schemas (from document arrays and single nested subdocs)
* and their corresponding compiled models. Each element of the array is
* an object with 2 properties: `schema` and `model`.
*
* This property is typically only useful for plugin authors and advanced users.
* You do not need to interact with this property at all to use mongoose.
*
* @api public
* @property childSchemas
* @memberOf Schema
* @instance
*/
Object.defineProperty(Schema.prototype, 'childSchemas', {
configurable: false,
enumerable: true,
writable: true
});
/**
* Object containing all virtuals defined on this schema.
* The objects' keys are the virtual paths and values are instances of `VirtualType`.
*
* This property is typically only useful for plugin authors and advanced users.
* You do not need to interact with this property at all to use mongoose.
*
* #### Example:
*
* const schema = new Schema({});
* schema.virtual('answer').get(() => 42);
*
* console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
* console.log(schema.virtuals['answer'].getters[0].call()); // 42
*
* @api public
* @property virtuals
* @memberOf Schema
* @instance
*/
Object.defineProperty(Schema.prototype, 'virtuals', {
configurable: false,
enumerable: true,
writable: true
});
/**
* The original object passed to the schema constructor
*
* #### Example:
*
* const schema = new Schema({ a: String }).add({ b: String });
* schema.obj; // { a: String }
*
* @api public
* @property obj
* @memberOf Schema
* @instance
*/
Schema.prototype.obj;
/**
* The paths defined on this schema. The keys are the top-level paths
* in this schema, and the values are instances of the SchemaType class.
*
* #### Example:
*
* const schema = new Schema({ name: String }, { _id: false });
* schema.paths; // { name: SchemaString { ... } }
*
* schema.add({ age: Number });
* schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
*
* @api public
* @property paths
* @memberOf Schema
* @instance
*/
Schema.prototype.paths;
/**
* Schema as a tree
*
* #### Example:
*
* {
* '_id' : ObjectId
* , 'nested' : {
* 'key' : String
* }
* }
*
* @api private
* @property tree
* @memberOf Schema
* @instance
*/
Schema.prototype.tree;
/**
* Returns a deep copy of the schema
*
* #### Example:
*
* const schema = new Schema({ name: String });
* const clone = schema.clone();
* clone === schema; // false
* clone.path('name'); // SchemaString { ... }
*
* @return {Schema} the cloned schema
* @api public
* @memberOf Schema
* @instance
*/
Schema.prototype.clone = function() {
const s = this._clone();
// Bubble up `init` for backwards compat
s.on('init', v => this.emit('init', v));
return s;
};
/*!
* ignore
*/
Schema.prototype._clone = function _clone(Constructor) {
Constructor = Constructor || (this.base == null ? Schema : this.base.Schema);
const s = new Constructor({}, this._userProvidedOptions);
s.base = this.base;
s.obj = this.obj;
s.options = clone(this.options);
s.callQueue = this.callQueue.map(function(f) { return f; });
s.methods = clone(this.methods);
s.methodOptions = clone(this.methodOptions);
s.statics = clone(this.statics);
s.query = clone(this.query);
s.plugins = Array.prototype.slice.call(this.plugins);
s._indexes = clone(this._indexes);
s._searchIndexes = clone(this._searchIndexes);
s.s.hooks = this.s.hooks.clone();
s.tree = clone(this.tree);
s.paths = Object.fromEntries(
Object.entries(this.paths).map(([key, value]) => ([key, value.clone()]))
);
s.nested = clone(this.nested);
s.subpaths = clone(this.subpaths);
for (const schemaType of Object.values(s.paths)) {
if (schemaType.$isSingleNested) {
const path = schemaType.path;
for (const key of Object.keys(schemaType.schema.paths)) {
s.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
}
for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
s.singleNestedPaths[path + '.' + key] =
schemaType.schema.singleNestedPaths[key];
}
for (const key of Object.keys(schemaType.schema.subpaths)) {
s.singleNestedPaths[path + '.' + key] =
schemaType.schema.subpaths[key];
}
for (const key of Object.keys(schemaType.schema.nested)) {
s.singleNestedPaths[path + '.' + key] = 'nested';
}
}
}
s.childSchemas = gatherChildSchemas(s);
s.virtuals = clone(this.virtuals);
s.$globalPluginsApplied = this.$globalPluginsApplied;
s.$isRootDiscriminator = this.$isRootDiscriminator;
s.$implicitlyCreated = this.$implicitlyCreated;
s.$id = ++id;
s.$originalSchemaId = this.$id;
s.mapPaths = [].concat(this.mapPaths);
if (this.discriminatorMapping != null) {
s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
}
if (this.discriminators != null) {
s.discriminators = Object.assign({}, this.discriminators);
}
if (this._applyDiscriminators != null) {
s._applyDiscriminators = new Map(this._applyDiscriminators);
}
s.aliases = Object.assign({}, this.aliases);
return s;
};
/**
* Returns a new schema that has the picked `paths` from this schema.
*
* This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas.
*
* #### Example:
*
* const schema = Schema({ name: String, age: Number });
* // Creates a new schema with the same `name` path as `schema`,
* // but no `age` path.
* const newSchema = schema.pick(['name']);
*
* newSchema.path('name'); // SchemaString { ... }
* newSchema.path('age'); // undefined
*
* @param {String[]} paths List of Paths to pick for the new Schema
* @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
* @return {Schema}
* @api public
*/
Schema.prototype.pick = function(paths, options) {
const newSchema = new Schema({}, options || this.options);
if (!Array.isArray(paths)) {
throw new MongooseError('Schema#pick() only accepts an array argument, ' +
'got "' + typeof paths + '"');
}
for (const path of paths) {
if (this.nested[path]) {
newSchema.add({ [path]: get(this.tree, path) });
} else {
const schematype = this.path(path);
if (schematype == null) {
throw new MongooseError('Path `' + path + '` is not in the schema');
}
newSchema.add({ [path]: schematype });
}
}
return newSchema;
};
/**
* Returns a new schema that has the `paths` from the original schema, minus the omitted ones.
*
* This method is analagous to [Lodash's `omit()` function](https://lodash.com/docs/#omit) for Mongoose schemas.
*
* #### Example:
*
* const schema = Schema({ name: String, age: Number });
* // Creates a new schema omitting the `age` path
* const newSchema = schema.omit(['age']);
*
* newSchema.path('name'); // SchemaString { ... }
* newSchema.path('age'); // undefined
*
* @param {String[]} paths List of Paths to omit for the new Schema
* @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
* @return {Schema}
* @api public
*/
Schema.prototype.omit = function(paths, options) {
const newSchema = new Schema(this, options || this.options);
if (!Array.isArray(paths)) {
throw new MongooseError(
'Schema#omit() only accepts an array argument, ' +
'got "' +
typeof paths +
'"'
);
}
newSchema.remove(paths);
for (const nested in newSchema.singleNestedPaths) {
if (paths.includes(nested)) {
delete newSchema.singleNestedPaths[nested];
}
}
return newSchema;
};
/**
* Returns default options for this schema, merged with `options`.
*
* @param {Object} [options] Options to overwrite the default options
* @return {Object} The merged options of `options` and the default options
* @api private
*/
Schema.prototype.defaultOptions = function(options) {
this._userProvidedOptions = options == null ? {} : clone(options);
const baseOptions = this.base && this.base.options || {};
const strict = 'strict' in baseOptions ? baseOptions.strict : true;
const strictQuery = 'strictQuery' in baseOptions ? baseOptions.strictQuery : false;
const id = 'id' in baseOptions ? baseOptions.id : true;
options = {
strict,
strictQuery,
bufferCommands: true,
capped: false, // { size, max, autoIndexId }
versionKey: '__v',
optimisticConcurrency: false,
minimize: true,
autoIndex: null,
discriminatorKey: '__t',
shardKey: null,
read: null,
validateBeforeSave: true,
validateModifiedOnly: false,
// the following are only applied at construction time
_id: true,
id: id,
typeKey: 'type',
...options
};
if (options.versionKey && typeof options.versionKey !== 'string') {
throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`');
}
if (typeof options.read === 'string') {
options.read = handleReadPreferenceAliases(options.read);
} else if (Array.isArray(options.read) && typeof options.read[0] === 'string') {
options.read = {
mode: handleReadPreferenceAliases(options.read[0]),
tags: options.read[1]
};
}
if (options.optimisticConcurrency && !options.versionKey) {
throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
}
return options;
};
/**
* Inherit a Schema by applying a discriminator on an existing Schema.
*
*
* #### Example:
*
* const eventSchema = new mongoose.Schema({ timestamp: Date }, { discriminatorKey: 'kind' });
*
* const clickedEventSchema = new mongoose.Schema({ element: String }, { discriminatorKey: 'kind' });
* const ClickedModel = eventSchema.discriminator('clicked', clickedEventSchema);
*
* const Event = mongoose.model('Event', eventSchema);
*
* Event.discriminators['clicked']; // Model { clicked }
*
* const doc = await Event.create({ kind: 'clicked', element: '#hero' });
* doc.element; // '#hero'
* doc instanceof ClickedModel; // true
*
* @param {String} name the name of the discriminator
* @param {Schema} schema the discriminated Schema
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.discriminator = function(name, schema) {
this._applyDiscriminators = this._applyDiscriminators || new Map();
this._applyDiscriminators.set(name, schema);
return this;
};
/**
* Adds key path / schema type pairs to this schema.
*
* #### Example:
*
* const ToySchema = new Schema();
* ToySchema.add({ name: 'string', color: 'string', price: 'number' });
*
* const TurboManSchema = new Schema();
* // You can also `add()` another schema and copy over all paths, virtuals,
* // getters, setters, indexes, methods, and statics.
* TurboManSchema.add(ToySchema).add({ year: Number });
*
* @param {Object|Schema} obj plain object with paths to add, or another schema
* @param {String} [prefix] path to prefix the newly added paths with
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.add = function add(obj, prefix) {
if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
merge(this, obj);
return this;
}
// Special case: setting top-level `_id` to false should convert to disabling
// the `_id` option. This behavior never worked before 5.4.11 but numerous
// codebases use it (see gh-7516, gh-7512).
if (obj._id === false && prefix == null) {
this.options._id = false;
}
prefix = prefix || '';
// avoid prototype pollution
if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
return this;
}
const keys = Object.keys(obj);
const typeKey = this.options.typeKey;
for (const key of keys) {
if (utils.specialProperties.has(key)) {
continue;
}
const fullPath = prefix + key;
const val = obj[key];
if (val == null) {
throw new TypeError('Invalid value for schema path `' + fullPath +
'`, got value "' + val + '"');
}
// Retain `_id: false` but don't set it as a path, re: gh-8274.
if (key === '_id' && val === false) {
continue;
}
// Deprecate setting schema paths to primitive types (gh-7558)
let isMongooseTypeString = false;
if (typeof val === 'string') {
// Handle the case in which the type is specified as a string (eg. 'date', 'oid', ...)
const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
const upperVal = val.charAt(0).toUpperCase() + val.substring(1);
isMongooseTypeString = MongooseTypes[upperVal] != null;
}
if (
key !== '_id' &&
((typeof val !== 'object' && typeof val !== 'function' && !isMongooseTypeString) ||
val == null)
) {
throw new TypeError(`Invalid schema configuration: \`${val}\` is not ` +
`a valid type at path \`${key}\`. See ` +
'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
}
if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === 'VirtualType') {
this.virtual(val);
continue;
}
if (Array.isArray(val) && val.length === 1 && val[0] == null) {
throw new TypeError('Invalid value for schema Array path `' + fullPath +
'`, got value "' + val[0] + '"');
}
if (!(isPOJO(val) || val instanceof SchemaTypeOptions)) {
// Special-case: Non-options definitely a path so leaf at this node
// Examples: Schema instances, SchemaType instances
if (prefix) {
this.nested[prefix.substring(0, prefix.length - 1)] = true;
}
this.path(prefix + key, val);
if (val[0] != null && !(val[0].instanceOfSchema) && utils.isPOJO(val[0].discriminators)) {
const schemaType = this.path(prefix + key);
for (const key in val[0].discriminators) {
schemaType.discriminator(key, val[0].discriminators[key]);
}
}
} else if (Object.keys(val).length < 1) {
// Special-case: {} always interpreted as Mixed path so leaf at this node
if (prefix) {
this.nested[prefix.substring(0, prefix.length - 1)] = true;
}
this.path(fullPath, val); // mixed type
} else if (!val[typeKey] || (typeKey === 'type' && isPOJO(val.type) && val.type.type)) {
// Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse
// nested object `{ last: { name: String } }`. Avoid functions with `.type` re: #10807 because
// NestJS sometimes adds `Date.type`.
this.nested[fullPath] = true;
this.add(val, fullPath + '.');
} else {
// There IS a bona-fide type key that may also be a POJO
const _typeDef = val[typeKey];
if (isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) {
// If a POJO is the value of a type key, make it a subdocument
if (prefix) {
this.nested[prefix.substring(0, prefix.length - 1)] = true;
}
const childSchemaOptions = {};
if (this._userProvidedOptions.typeKey) {
childSchemaOptions.typeKey = this._userProvidedOptions.typeKey;
}
// propagate 'strict' option to child schema
if (this._userProvidedOptions.strict != null) {
childSchemaOptions.strict = this._userProvidedOptions.strict;
}
if (this._userProvidedOptions.toObject != null) {
childSchemaOptions.toObject = utils.omit(this._userProvidedOptions.toObject, ['transform']);
}
if (this._userProvidedOptions.toJSON != null) {
childSchemaOptions.toJSON = utils.omit(this._userProvidedOptions.toJSON, ['transform']);
}
const _schema = new Schema(_typeDef, childSchemaOptions);
_schema.$implicitlyCreated = true;
const schemaWrappedPath = Object.assign({}, val, { [typeKey]: _schema });
this.path(prefix + key, schemaWrappedPath);
} else {
// Either the type is non-POJO or we interpret it as Mixed anyway
if (prefix) {
this.nested[prefix.substring(0, prefix.length - 1)] = true;
}
this.path(prefix + key, val);
if (val != null && !(val.instanceOfSchema) && utils.isPOJO(val.discriminators)) {
const schemaType = this.path(prefix + key);
for (const key in val.discriminators) {
schemaType.discriminator(key, val.discriminators[key]);
}
}
}
}
}
const aliasObj = Object.fromEntries(
Object.entries(obj).map(([key]) => ([prefix + key, null]))
);
aliasFields(this, aliasObj);
return this;
};
/**
* Add an alias for `path`. This means getting or setting the `alias`
* is equivalent to getting or setting the `path`.
*
* #### Example:
*
* const toySchema = new Schema({ n: String });
*
* // Make 'name' an alias for 'n'
* toySchema.alias('n', 'name');
*
* const Toy = mongoose.model('Toy', toySchema);
* const turboMan = new Toy({ n: 'Turbo Man' });
*
* turboMan.name; // 'Turbo Man'
* turboMan.n; // 'Turbo Man'
*
* turboMan.name = 'Turbo Man Action Figure';
* turboMan.n; // 'Turbo Man Action Figure'
*
* await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' }
*
*
* @param {String} path real path to alias
* @param {String|String[]} alias the path(s) to use as an alias for `path`
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.alias = function alias(path, alias) {
aliasFields(this, { [path]: alias });
return this;
};
/**
* Remove an index by name or index specification.
*
* removeIndex only removes indexes from your schema object. Does **not** affect the indexes
* in MongoDB.
*
* #### Example:
*
* const ToySchema = new Schema({ name: String, color: String, price: Number });
*
* // Add a new index on { name, color }
* ToySchema.index({ name: 1, color: 1 });
*
* // Remove index on { name, color }
* // Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index
* ToySchema.removeIndex({ name: 1, color: 1 });
*
* // Add an index with a custom name
* ToySchema.index({ color: 1 }, { name: 'my custom index name' });
* // Remove index by name
* ToySchema.removeIndex('my custom index name');
*
* @param {Object|string} index name or index specification
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.removeIndex = function removeIndex(index) {
if (arguments.length > 1) {
throw new Error('removeIndex() takes only 1 argument');
}
if (typeof index !== 'object' && typeof index !== 'string') {
throw new Error('removeIndex() may only take either an object or a string as an argument');
}
if (typeof index === 'object') {
for (let i = this._indexes.length - 1; i >= 0; --i) {
if (util.isDeepStrictEqual(this._indexes[i][0], index)) {
this._indexes.splice(i, 1);
}
}
} else {
for (let i = this._indexes.length - 1; i >= 0; --i) {
if (this._indexes[i][1] != null && this._indexes[i][1].name === index) {
this._indexes.splice(i, 1);
}
}
}
return this;
};
/**
* Remove all indexes from this schema.
*
* clearIndexes only removes indexes from your schema object. Does **not** affect the indexes
* in MongoDB.
*
* #### Example:
*
* const ToySchema = new Schema({ name: String, color: String, price: Number });
* ToySchema.index({ name: 1 });
* ToySchema.index({ color: 1 });
*
* // Remove all indexes on this schema
* ToySchema.clearIndexes();
*
* ToySchema.indexes(); // []
*
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.clearIndexes = function clearIndexes() {
this._indexes.length = 0;
return this;
};
/**
* Add an [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) that Mongoose will create using `Model.createSearchIndex()`.
* This function only works when connected to MongoDB Atlas.
*
* #### Example:
*
* const ToySchema = new Schema({ name: String, color: String, price: Number });
* ToySchema.searchIndex({ name: 'test', definition: { mappings: { dynamic: true } } });
*
* @param {Object} description index options, including `name` and `definition`
* @param {String} description.name
* @param {Object} description.definition
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.searchIndex = function searchIndex(description) {
this._searchIndexes.push(description);
return this;
};
/**
* Reserved document keys.
*
* Keys in this object are names that are warned in schema declarations
* because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema
* using `new Schema()` with one of these property names, Mongoose will log a warning.
*
* - _posts
* - _pres
* - collection
* - emit
* - errors
* - get
* - init
* - isModified
* - isNew
* - listeners
* - modelName
* - on
* - once
* - populated
* - prototype
* - remove
* - removeListener
* - save
* - schema
* - toObject
* - validate
*
* _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.
*
* const schema = new Schema(..);
* schema.methods.init = function () {} // potentially breaking
*
* @property reserved
* @memberOf Schema
* @static
*/
Schema.reserved = Object.create(null);
Schema.prototype.reserved = Schema.reserved;
const reserved = Schema.reserved;
// Core object
reserved['prototype'] =
// EventEmitter
reserved.emit =
reserved.listeners =
reserved.removeListener =
// document properties and functions
reserved.collection =
reserved.errors =
reserved.get =
reserved.init =
reserved.isModified =
reserved.isNew =
reserved.populated =
reserved.remove =
reserved.save =
reserved.toObject =
reserved.validate = 1;
reserved.collection = 1;
/**
* Gets/sets schema paths.