123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160 |
- 'use strict';
- 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 arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol;
- const get = require('./helpers/get');
- const getIndexes = require('./helpers/schema/getIndexes');
- const merge = require('./helpers/schema/merge');
- const mpath = require('mpath');
- const readPref = require('./driver').get().ReadPreference;
- const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
- const util = require('util');
- const utils = require('./utils');
- const validateRef = require('./helpers/populate/validateRef');
- let MongooseTypes;
- const queryHooks = require('./helpers/query/applyQueryMiddleware').
- middlewareFunctions;
- const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
- const hookNames = queryHooks.concat(documentHooks).
- reduce((s, hook) => s.add(hook), new Set());
- let id = 0;
- 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.methods = {};
- this.methodOptions = {};
- this.statics = {};
- this.tree = {};
- this.query = {};
- this.childSchemas = [];
- this.plugins = [];
-
- this.$id = ++id;
- this.mapPaths = [];
- this.s = {
- hooks: new Kareem()
- };
- this.options = this.defaultOptions(options);
-
- if (Array.isArray(obj)) {
- for (const definition of obj) {
- this.add(definition);
- }
- } else if (obj) {
- this.add(obj);
- }
-
- const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
-
- const auto_id = !this.paths['_id'] &&
- (!this.options.noId && this.options._id) && !_idSubDoc;
- if (auto_id) {
- addAutoId(this);
- }
- this.setupTimestamp(this.options.timestamps);
- }
- function aliasFields(schema, paths) {
- paths = paths || Object.keys(schema.paths);
- for (const path of paths) {
- const options = get(schema.paths[path], 'options');
- if (options == null) {
- continue;
- }
- const prop = schema.paths[path].path;
- const alias = options.alias;
- if (!alias) {
- 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));
- }
- }
- Schema.prototype = Object.create(EventEmitter.prototype);
- Schema.prototype.constructor = Schema;
- Schema.prototype.instanceOfSchema = true;
- Object.defineProperty(Schema.prototype, '$schemaType', {
- configurable: false,
- enumerable: false,
- writable: true
- });
- Object.defineProperty(Schema.prototype, 'childSchemas', {
- configurable: false,
- enumerable: true,
- writable: true
- });
- Schema.prototype.obj;
- Schema.prototype.paths;
- Schema.prototype.tree;
- Schema.prototype.clone = function() {
- const Constructor = this.base == null ? Schema : this.base.Schema;
- const s = new Constructor({}, this._userProvidedOptions);
- s.base = this.base;
- s.obj = this.obj;
- s.options = utils.clone(this.options);
- s.callQueue = this.callQueue.map(function(f) { return f; });
- s.methods = utils.clone(this.methods);
- s.methodOptions = utils.clone(this.methodOptions);
- s.statics = utils.clone(this.statics);
- s.query = utils.clone(this.query);
- s.plugins = Array.prototype.slice.call(this.plugins);
- s._indexes = utils.clone(this._indexes);
- s.s.hooks = this.s.hooks.clone();
- s.tree = utils.clone(this.tree);
- s.paths = utils.clone(this.paths);
- s.nested = utils.clone(this.nested);
- s.subpaths = utils.clone(this.subpaths);
- s.singleNestedPaths = utils.clone(this.singleNestedPaths);
- s.childSchemas = gatherChildSchemas(s);
- s.virtuals = utils.clone(this.virtuals);
- s.$globalPluginsApplied = this.$globalPluginsApplied;
- s.$isRootDiscriminator = this.$isRootDiscriminator;
- s.$implicitlyCreated = this.$implicitlyCreated;
- 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);
- }
- s.aliases = Object.assign({}, this.aliases);
-
- s.on('init', v => this.emit('init', v));
- return s;
- };
- 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;
- };
- Schema.prototype.defaultOptions = function(options) {
- if (options && options.safe === false) {
- options.safe = { w: 0 };
- }
- if (options && options.safe && options.safe.w === 0) {
-
- options.versionKey = false;
- }
- this._userProvidedOptions = options == null ? {} : utils.clone(options);
- const baseOptions = get(this, 'base.options', {});
- options = utils.options({
- strict: 'strict' in baseOptions ? baseOptions.strict : true,
- strictQuery: 'strictQuery' in baseOptions ? baseOptions.strictQuery : false,
- bufferCommands: true,
- capped: false,
- versionKey: '__v',
- optimisticConcurrency: false,
- discriminatorKey: '__t',
- minimize: true,
- autoIndex: null,
- shardKey: null,
- read: null,
- validateBeforeSave: true,
-
- noId: false,
- _id: true,
- noVirtualId: false,
- id: true,
- typeKey: 'type',
- typePojoToMixed: 'typePojoToMixed' in baseOptions ? baseOptions.typePojoToMixed : true
- }, utils.clone(options));
- if (options.read) {
- options.read = readPref(options.read);
- }
- if (options.optimisticConcurrency && !options.versionKey) {
- throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
- }
- return options;
- };
- Schema.prototype.add = function add(obj, prefix) {
- if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
- merge(this, obj);
- return this;
- }
-
-
-
- if (obj._id === false && prefix == null) {
- this.options._id = false;
- }
- prefix = prefix || '';
-
- if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
- return this;
- }
- const keys = Object.keys(obj);
- for (const key of keys) {
- const fullPath = prefix + key;
- if (obj[key] == null) {
- throw new TypeError('Invalid value for schema path `' + fullPath +
- '`, got value "' + obj[key] + '"');
- }
-
- if (key === '_id' && obj[key] === false) {
- continue;
- }
- if (obj[key] instanceof VirtualType || get(obj[key], 'constructor.name', null) === 'VirtualType') {
- this.virtual(obj[key]);
- continue;
- }
- if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) {
- throw new TypeError('Invalid value for schema Array path `' + fullPath +
- '`, got value "' + obj[key][0] + '"');
- }
- if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) {
-
-
- if (prefix) {
- this.nested[prefix.substr(0, prefix.length - 1)] = true;
- }
- this.path(prefix + key, obj[key]);
- } else if (Object.keys(obj[key]).length < 1) {
-
- if (prefix) {
- this.nested[prefix.substr(0, prefix.length - 1)] = true;
- }
- this.path(fullPath, obj[key]);
- } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type)) {
-
-
- this.nested[fullPath] = true;
- this.add(obj[key], fullPath + '.');
- } else {
-
- if (!this.options.typePojoToMixed && utils.isPOJO(obj[key][this.options.typeKey])) {
-
- if (prefix) {
- this.nested[prefix.substr(0, prefix.length - 1)] = true;
- }
-
- const opts = { typePojoToMixed: false };
- const _schema = new Schema(obj[key][this.options.typeKey], opts);
- const schemaWrappedPath = Object.assign({}, obj[key], { [this.options.typeKey]: _schema });
- this.path(prefix + key, schemaWrappedPath);
- } else {
-
- if (prefix) {
- this.nested[prefix.substr(0, prefix.length - 1)] = true;
- }
- this.path(prefix + key, obj[key]);
- }
- }
- }
- const addedKeys = Object.keys(obj).
- map(key => prefix ? prefix + key : key);
- aliasFields(this, addedKeys);
- return this;
- };
- Schema.reserved = Object.create(null);
- Schema.prototype.reserved = Schema.reserved;
- const reserved = Schema.reserved;
- reserved['prototype'] =
- reserved.emit =
- reserved.listeners =
- reserved.on =
- reserved.removeListener =
- reserved.collection =
- reserved.errors =
- reserved.get =
- reserved.init =
- reserved.isModified =
- reserved.isNew =
- reserved.populated =
- reserved.remove =
- reserved.save =
- reserved.toObject =
- reserved.validate = 1;
- Schema.prototype.path = function(path, obj) {
-
- const cleanPath = _pathToPositionalSyntax(path);
- if (obj === undefined) {
- let schematype = _getPath(this, path, cleanPath);
- if (schematype != null) {
- return schematype;
- }
-
- const mapPath = getMapPath(this, path);
- if (mapPath != null) {
- return mapPath;
- }
-
- schematype = this.hasMixedParent(cleanPath);
- if (schematype != null) {
- return schematype;
- }
-
- return /\.\d+\.?.*$/.test(path)
- ? getPositionalPath(this, path)
- : undefined;
- }
-
- const firstPieceOfPath = path.split('.')[0];
- if (reserved[firstPieceOfPath]) {
- throw new Error('`' + firstPieceOfPath + '` may not be used as a schema pathname');
- }
- if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
- validateRef(obj.ref, path);
- }
-
- const subpaths = path.split(/\./);
- const last = subpaths.pop();
- let branch = this.tree;
- let fullPath = '';
- for (const sub of subpaths) {
- fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub;
- if (!branch[sub]) {
- this.nested[fullPath] = true;
- branch[sub] = {};
- }
- if (typeof branch[sub] !== 'object') {
- const msg = 'Cannot set nested path `' + path + '`. '
- + 'Parent path `'
- + fullPath
- + '` already set to type ' + branch[sub].name
- + '.';
- throw new Error(msg);
- }
- branch = branch[sub];
- }
- branch[last] = utils.clone(obj);
- this.paths[path] = this.interpretAsType(path, obj, this.options);
- const schemaType = this.paths[path];
- if (schemaType.$isSchemaMap) {
-
-
-
- const mapPath = path + '.$*';
- let _mapType = { type: {} };
- if (utils.hasUserDefinedProperty(obj, 'of')) {
- const isInlineSchema = utils.isPOJO(obj.of) &&
- Object.keys(obj.of).length > 0 &&
- !utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
- _mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
- }
- this.paths[mapPath] = this.interpretAsType(mapPath,
- _mapType, this.options);
- this.mapPaths.push(this.paths[mapPath]);
- schemaType.$__schemaType = this.paths[mapPath];
- }
- if (schemaType.$isSingleNested) {
- for (const key of Object.keys(schemaType.schema.paths)) {
- this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
- }
- for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
- this.singleNestedPaths[path + '.' + key] =
- schemaType.schema.singleNestedPaths[key];
- }
- for (const key of Object.keys(schemaType.schema.subpaths)) {
- this.singleNestedPaths[path + '.' + key] =
- schemaType.schema.subpaths[key];
- }
- for (const key of Object.keys(schemaType.schema.nested)) {
- this.singleNestedPaths[path + '.' + key] = 'nested';
- }
- Object.defineProperty(schemaType.schema, 'base', {
- configurable: true,
- enumerable: false,
- writable: false,
- value: this.base
- });
- schemaType.caster.base = this.base;
- this.childSchemas.push({
- schema: schemaType.schema,
- model: schemaType.caster
- });
- } else if (schemaType.$isMongooseDocumentArray) {
- Object.defineProperty(schemaType.schema, 'base', {
- configurable: true,
- enumerable: false,
- writable: false,
- value: this.base
- });
- schemaType.casterConstructor.base = this.base;
- this.childSchemas.push({
- schema: schemaType.schema,
- model: schemaType.casterConstructor
- });
- }
- if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) {
- let arrayPath = path;
- let _schemaType = schemaType;
- const toAdd = [];
- while (_schemaType.$isMongooseArray) {
- arrayPath = arrayPath + '.$';
-
- if (_schemaType.$isMongooseDocumentArray) {
- _schemaType.$embeddedSchemaType._arrayPath = arrayPath;
- _schemaType.$embeddedSchemaType._arrayParentPath = path;
- _schemaType = _schemaType.$embeddedSchemaType.clone();
- } else {
- _schemaType.caster._arrayPath = arrayPath;
- _schemaType.caster._arrayParentPath = path;
- _schemaType = _schemaType.caster.clone();
- }
- _schemaType.path = arrayPath;
- toAdd.push(_schemaType);
- }
- for (const _schemaType of toAdd) {
- this.subpaths[_schemaType.path] = _schemaType;
- }
- }
- if (schemaType.$isMongooseDocumentArray) {
- for (const key of Object.keys(schemaType.schema.paths)) {
- this.subpaths[path + '.' + key] = schemaType.schema.paths[key];
- schemaType.schema.paths[key].$isUnderneathDocArray = true;
- }
- for (const key of Object.keys(schemaType.schema.subpaths)) {
- this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key];
- schemaType.schema.subpaths[key].$isUnderneathDocArray = true;
- }
- for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
- const _schemaType = schemaType.schema.singleNestedPaths[key];
- this.subpaths[path + '.' + key] = _schemaType;
- if (typeof _schemaType === 'object' && _schemaType != null) {
- _schemaType.$isUnderneathDocArray = true;
- }
- }
- }
- return this;
- };
- function gatherChildSchemas(schema) {
- const childSchemas = [];
- for (const path of Object.keys(schema.paths)) {
- const schematype = schema.paths[path];
- if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
- childSchemas.push({ schema: schematype.schema, model: schematype.caster });
- }
- }
- return childSchemas;
- }
- function _getPath(schema, path, cleanPath) {
- if (schema.paths.hasOwnProperty(path)) {
- return schema.paths[path];
- }
- if (schema.subpaths.hasOwnProperty(cleanPath)) {
- return schema.subpaths[cleanPath];
- }
- if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
- return schema.singleNestedPaths[cleanPath];
- }
- return null;
- }
- function _pathToPositionalSyntax(path) {
- if (!/\.\d+/.test(path)) {
- return path;
- }
- return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$');
- }
- function getMapPath(schema, path) {
- if (schema.mapPaths.length === 0) {
- return null;
- }
- for (const val of schema.mapPaths) {
- const _path = val.path;
- const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
- if (re.test(path)) {
- return schema.paths[_path];
- }
- }
- return null;
- }
- Object.defineProperty(Schema.prototype, 'base', {
- configurable: true,
- enumerable: false,
- writable: true,
- value: null
- });
- Schema.prototype.interpretAsType = function(path, obj, options) {
- if (obj instanceof SchemaType) {
- if (obj.path === path) {
- return obj;
- }
- const clone = obj.clone();
- clone.path = path;
- return clone;
- }
-
-
- const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
- if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) {
- const constructorName = utils.getFunctionName(obj.constructor);
- if (constructorName !== 'Object') {
- const oldObj = obj;
- obj = {};
- obj[options.typeKey] = oldObj;
- }
- }
-
-
-
- let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type)
- ? obj[options.typeKey]
- : {};
- let name;
- if (utils.isPOJO(type) || type === 'mixed') {
- return new MongooseTypes.Mixed(path, obj);
- }
- if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) {
-
- let cast = (type === Array || type === 'array')
- ? obj.cast || obj.of
- : type[0];
- if (cast && cast.instanceOfSchema) {
- return new MongooseTypes.DocumentArray(path, cast, obj);
- }
- if (cast &&
- cast[options.typeKey] &&
- cast[options.typeKey].instanceOfSchema) {
- return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
- }
- if (Array.isArray(cast)) {
- return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
- }
- if (typeof cast === 'string') {
- cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
- } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type))
- && utils.isPOJO(cast)) {
- if (Object.keys(cast).length) {
-
-
-
- const childSchemaOptions = { minimize: options.minimize };
- if (options.typeKey) {
- childSchemaOptions.typeKey = options.typeKey;
- }
-
- if (options.hasOwnProperty('strict')) {
- childSchemaOptions.strict = options.strict;
- }
- if (options.hasOwnProperty('typePojoToMixed')) {
- childSchemaOptions.typePojoToMixed = options.typePojoToMixed;
- }
- if (this._userProvidedOptions.hasOwnProperty('_id')) {
- childSchemaOptions._id = this._userProvidedOptions._id;
- } else if (Schema.Types.DocumentArray.defaultOptions &&
- Schema.Types.DocumentArray.defaultOptions._id != null) {
- childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id;
- }
- const childSchema = new Schema(cast, childSchemaOptions);
- childSchema.$implicitlyCreated = true;
- return new MongooseTypes.DocumentArray(path, childSchema, obj);
- } else {
-
- return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
- }
- }
- if (cast) {
- type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
- ? cast[options.typeKey]
- : cast;
- name = typeof type === 'string'
- ? type
- : type.schemaName || utils.getFunctionName(type);
-
- if (name === 'ClockDate') {
- name = 'Date';
- }
- if (!MongooseTypes.hasOwnProperty(name)) {
- throw new TypeError('Invalid schema configuration: ' +
- `\`${name}\` is not a valid type within the array \`${path}\`.` +
- 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.');
- }
- }
- return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
- }
- if (type && type.instanceOfSchema) {
- return new MongooseTypes.Embedded(type, path, obj);
- }
- if (Buffer.isBuffer(type)) {
- name = 'Buffer';
- } else if (typeof type === 'function' || typeof type === 'object') {
- name = type.schemaName || utils.getFunctionName(type);
- } else {
- name = type == null ? '' + type : type.toString();
- }
- if (name) {
- name = name.charAt(0).toUpperCase() + name.substring(1);
- }
-
-
- if (name === 'ObjectID') {
- name = 'ObjectId';
- }
-
- if (name === 'ClockDate') {
- name = 'Date';
- }
- if (MongooseTypes[name] == null) {
- throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
- `a valid type at path \`${path}\`. See ` +
- 'http://bit.ly/mongoose-schematypes for a list of valid schema types.');
- }
- return new MongooseTypes[name](path, obj);
- };
- Schema.prototype.eachPath = function(fn) {
- const keys = Object.keys(this.paths);
- const len = keys.length;
- for (let i = 0; i < len; ++i) {
- fn(keys[i], this.paths[keys[i]]);
- }
- return this;
- };
- Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
- if (this._requiredpaths && !invalidate) {
- return this._requiredpaths;
- }
- const paths = Object.keys(this.paths);
- let i = paths.length;
- const ret = [];
- while (i--) {
- const path = paths[i];
- if (this.paths[path].isRequired) {
- ret.push(path);
- }
- }
- this._requiredpaths = ret;
- return this._requiredpaths;
- };
- Schema.prototype.indexedPaths = function indexedPaths() {
- if (this._indexedpaths) {
- return this._indexedpaths;
- }
- this._indexedpaths = this.indexes();
- return this._indexedpaths;
- };
- Schema.prototype.pathType = function(path) {
-
- const cleanPath = _pathToPositionalSyntax(path);
- if (this.paths.hasOwnProperty(path)) {
- return 'real';
- }
- if (this.virtuals.hasOwnProperty(path)) {
- return 'virtual';
- }
- if (this.nested.hasOwnProperty(path)) {
- return 'nested';
- }
- if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
- return 'real';
- }
- const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path);
- if (singleNestedPath) {
- return singleNestedPath === 'nested' ? 'nested' : 'real';
- }
-
- const mapPath = getMapPath(this, path);
- if (mapPath != null) {
- return 'real';
- }
- if (/\.\d+\.|\.\d+$/.test(path)) {
- return getPositionalPathType(this, path);
- }
- return 'adhocOrUndefined';
- };
- Schema.prototype.hasMixedParent = function(path) {
- const subpaths = path.split(/\./g);
- path = '';
- for (let i = 0; i < subpaths.length; ++i) {
- path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
- if (this.paths.hasOwnProperty(path) &&
- this.paths[path] instanceof MongooseTypes.Mixed) {
- return this.paths[path];
- }
- }
- return null;
- };
- Schema.prototype.setupTimestamp = function(timestamps) {
- return setupTimestamps(this, timestamps);
- };
- function getPositionalPathType(self, path) {
- const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
- if (subpaths.length < 2) {
- return self.paths.hasOwnProperty(subpaths[0]) ?
- self.paths[subpaths[0]] :
- 'adhocOrUndefined';
- }
- let val = self.path(subpaths[0]);
- let isNested = false;
- if (!val) {
- return 'adhocOrUndefined';
- }
- const last = subpaths.length - 1;
- for (let i = 1; i < subpaths.length; ++i) {
- isNested = false;
- const subpath = subpaths[i];
- if (i === last && val && !/\D/.test(subpath)) {
- if (val.$isMongooseDocumentArray) {
- val = val.$embeddedSchemaType;
- } else if (val instanceof MongooseTypes.Array) {
-
- val = val.caster;
- } else {
- val = undefined;
- }
- break;
- }
-
- if (!/\D/.test(subpath)) {
-
- if (val instanceof MongooseTypes.Array && i !== last) {
- val = val.caster;
- }
- continue;
- }
- if (!(val && val.schema)) {
- val = undefined;
- break;
- }
- const type = val.schema.pathType(subpath);
- isNested = (type === 'nested');
- val = val.schema.path(subpath);
- }
- self.subpaths[path] = val;
- if (val) {
- return 'real';
- }
- if (isNested) {
- return 'nested';
- }
- return 'adhocOrUndefined';
- }
- function getPositionalPath(self, path) {
- getPositionalPathType(self, path);
- return self.subpaths[path];
- }
- Schema.prototype.queue = function(name, args) {
- this.callQueue.push([name, args]);
- return this;
- };
- Schema.prototype.pre = function(name) {
- if (name instanceof RegExp) {
- const remainingArgs = Array.prototype.slice.call(arguments, 1);
- for (const fn of hookNames) {
- if (name.test(fn)) {
- this.pre.apply(this, [fn].concat(remainingArgs));
- }
- }
- return this;
- }
- if (Array.isArray(name)) {
- const remainingArgs = Array.prototype.slice.call(arguments, 1);
- for (const el of name) {
- this.pre.apply(this, [el].concat(remainingArgs));
- }
- return this;
- }
- this.s.hooks.pre.apply(this.s.hooks, arguments);
- return this;
- };
- Schema.prototype.post = function(name) {
- if (name instanceof RegExp) {
- const remainingArgs = Array.prototype.slice.call(arguments, 1);
- for (const fn of hookNames) {
- if (name.test(fn)) {
- this.post.apply(this, [fn].concat(remainingArgs));
- }
- }
- return this;
- }
- if (Array.isArray(name)) {
- const remainingArgs = Array.prototype.slice.call(arguments, 1);
- for (const el of name) {
- this.post.apply(this, [el].concat(remainingArgs));
- }
- return this;
- }
- this.s.hooks.post.apply(this.s.hooks, arguments);
- return this;
- };
- Schema.prototype.plugin = function(fn, opts) {
- if (typeof fn !== 'function') {
- throw new Error('First param to `schema.plugin()` must be a function, ' +
- 'got "' + (typeof fn) + '"');
- }
- if (opts && opts.deduplicate) {
- for (const plugin of this.plugins) {
- if (plugin.fn === fn) {
- return this;
- }
- }
- }
- this.plugins.push({ fn: fn, opts: opts });
- fn(this, opts);
- return this;
- };
- Schema.prototype.method = function(name, fn, options) {
- if (typeof name !== 'string') {
- for (const i in name) {
- this.methods[i] = name[i];
- this.methodOptions[i] = utils.clone(options);
- }
- } else {
- this.methods[name] = fn;
- this.methodOptions[name] = utils.clone(options);
- }
- return this;
- };
- Schema.prototype.static = function(name, fn) {
- if (typeof name !== 'string') {
- for (const i in name) {
- this.statics[i] = name[i];
- }
- } else {
- this.statics[name] = fn;
- }
- return this;
- };
- Schema.prototype.index = function(fields, options) {
- fields || (fields = {});
- options || (options = {});
- if (options.expires) {
- utils.expires(options);
- }
- this._indexes.push([fields, options]);
- return this;
- };
- Schema.prototype.set = function(key, value, _tags) {
- if (arguments.length === 1) {
- return this.options[key];
- }
- switch (key) {
- case 'read':
- this.options[key] = readPref(value, _tags);
- this._userProvidedOptions[key] = this.options[key];
- break;
- case 'safe':
- setSafe(this.options, value);
- this._userProvidedOptions[key] = this.options[key];
- break;
- case 'timestamps':
- this.setupTimestamp(value);
- this.options[key] = value;
- this._userProvidedOptions[key] = this.options[key];
- break;
- case '_id':
- this.options[key] = value;
- this._userProvidedOptions[key] = this.options[key];
- if (value && !this.paths['_id']) {
- addAutoId(this);
- } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) {
- this.remove('_id');
- }
- break;
- default:
- this.options[key] = value;
- this._userProvidedOptions[key] = this.options[key];
- break;
- }
- return this;
- };
- const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' +
- 'deprecated. Use the `writeConcern` option instead: ' +
- 'http://bit.ly/mongoose-write-concern';
- const setSafe = util.deprecate(function setSafe(options, value) {
- options.safe = value === false ?
- { w: 0 } :
- value;
- }, safeDeprecationWarning);
- Schema.prototype.get = function(key) {
- return this.options[key];
- };
- const indexTypes = '2d 2dsphere hashed text'.split(' ');
- Object.defineProperty(Schema, 'indexTypes', {
- get: function() {
- return indexTypes;
- },
- set: function() {
- throw new Error('Cannot overwrite Schema.indexTypes');
- }
- });
- Schema.prototype.indexes = function() {
- return getIndexes(this);
- };
- Schema.prototype.virtual = function(name, options) {
- if (name instanceof VirtualType || (name != null && name.constructor.name === 'VirtualType')) {
- return this.virtual(name.path, name.options);
- }
- options = new VirtualOptions(options);
- if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
- if (options.localField == null) {
- throw new Error('Reference virtuals require `localField` option');
- }
- if (options.foreignField == null) {
- throw new Error('Reference virtuals require `foreignField` option');
- }
- this.pre('init', function(obj) {
- if (mpath.has(name, obj)) {
- const _v = mpath.get(name, obj);
- if (!this.$$populatedVirtuals) {
- this.$$populatedVirtuals = {};
- }
- if (options.justOne || options.count) {
- this.$$populatedVirtuals[name] = Array.isArray(_v) ?
- _v[0] :
- _v;
- } else {
- this.$$populatedVirtuals[name] = Array.isArray(_v) ?
- _v :
- _v == null ? [] : [_v];
- }
- mpath.unset(name, obj);
- }
- });
- const virtual = this.virtual(name);
- virtual.options = options;
- virtual.
- set(function(_v) {
- if (!this.$$populatedVirtuals) {
- this.$$populatedVirtuals = {};
- }
- if (options.justOne || options.count) {
- this.$$populatedVirtuals[name] = Array.isArray(_v) ?
- _v[0] :
- _v;
- if (typeof this.$$populatedVirtuals[name] !== 'object') {
- this.$$populatedVirtuals[name] = options.count ? _v : null;
- }
- } else {
- this.$$populatedVirtuals[name] = Array.isArray(_v) ?
- _v :
- _v == null ? [] : [_v];
- this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
- return doc && typeof doc === 'object';
- });
- }
- });
- if (typeof options.get === 'function') {
- virtual.get(options.get);
- }
- return virtual;
- }
- const virtuals = this.virtuals;
- const parts = name.split('.');
- if (this.pathType(name) === 'real') {
- throw new Error('Virtual path "' + name + '"' +
- ' conflicts with a real path in the schema');
- }
- virtuals[name] = parts.reduce(function(mem, part, i) {
- mem[part] || (mem[part] = (i === parts.length - 1)
- ? new VirtualType(options, name)
- : {});
- return mem[part];
- }, this.tree);
-
-
- let cur = parts[0];
- for (let i = 0; i < parts.length - 1; ++i) {
- if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) {
- const remnant = parts.slice(i + 1).join('.');
- const v = this.paths[cur].schema.virtual(remnant);
- v.get((v, virtual, doc) => {
- const parent = doc.__parentArray[arrayParentSymbol];
- const path = cur + '.' + doc.__index + '.' + remnant;
- return parent.get(path);
- });
- break;
- }
- cur += '.' + parts[i + 1];
- }
- return virtuals[name];
- };
- Schema.prototype.virtualpath = function(name) {
- return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
- };
- Schema.prototype.remove = function(path) {
- if (typeof path === 'string') {
- path = [path];
- }
- if (Array.isArray(path)) {
- path.forEach(function(name) {
- if (this.path(name) == null && !this.nested[name]) {
- return;
- }
- if (this.nested[name]) {
- const allKeys = Object.keys(this.paths).
- concat(Object.keys(this.nested));
- for (const path of allKeys) {
- if (path.startsWith(name + '.')) {
- delete this.paths[path];
- delete this.nested[path];
- _deletePath(this, path);
- }
- }
- delete this.nested[name];
- _deletePath(this, name);
- return;
- }
- delete this.paths[name];
- _deletePath(this, name);
- }, this);
- }
- return this;
- };
- function _deletePath(schema, name) {
- const pieces = name.split('.');
- const last = pieces.pop();
- let branch = schema.tree;
- for (const piece of pieces) {
- branch = branch[piece];
- }
- delete branch[last];
- }
- Schema.prototype.loadClass = function(model, virtualsOnly) {
- if (model === Object.prototype ||
- model === Function.prototype ||
- model.prototype.hasOwnProperty('$isMongooseModelPrototype')) {
- return this;
- }
- this.loadClass(Object.getPrototypeOf(model), virtualsOnly);
-
- if (!virtualsOnly) {
- Object.getOwnPropertyNames(model).forEach(function(name) {
- if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) {
- return;
- }
- const prop = Object.getOwnPropertyDescriptor(model, name);
- this.static(name, prop.value);
- }, this);
- }
-
- Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
- if (name.match(/^(constructor)$/)) {
- return;
- }
- const method = Object.getOwnPropertyDescriptor(model.prototype, name);
- if (!virtualsOnly) {
- if (typeof method.value === 'function') {
- this.method(name, method.value);
- }
- }
- if (typeof method.get === 'function') {
- if (this.virtuals[name]) {
- this.virtuals[name].getters = [];
- }
- this.virtual(name).get(method.get);
- }
- if (typeof method.set === 'function') {
- if (this.virtuals[name]) {
- this.virtuals[name].setters = [];
- }
- this.virtual(name).set(method.set);
- }
- }, this);
- return this;
- };
- Schema.prototype._getSchema = function(path) {
- const _this = this;
- const pathschema = _this.path(path);
- const resultPath = [];
- if (pathschema) {
- pathschema.$fullPath = path;
- return pathschema;
- }
- function search(parts, schema) {
- let p = parts.length + 1;
- let foundschema;
- let trypath;
- while (p--) {
- trypath = parts.slice(0, p).join('.');
- foundschema = schema.path(trypath);
- if (foundschema) {
- resultPath.push(trypath);
- if (foundschema.caster) {
-
- if (foundschema.caster instanceof MongooseTypes.Mixed) {
- foundschema.caster.$fullPath = resultPath.join('.');
- return foundschema.caster;
- }
-
-
-
-
-
-
- if (p !== parts.length) {
- if (foundschema.schema) {
- let ret;
- if (parts[p] === '$' || isArrayFilter(parts[p])) {
- if (p + 1 === parts.length) {
-
- return foundschema;
- }
-
- ret = search(parts.slice(p + 1), foundschema.schema);
- if (ret) {
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
- !foundschema.schema.$isSingleNested;
- }
- return ret;
- }
-
- ret = search(parts.slice(p), foundschema.schema);
- if (ret) {
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
- !foundschema.schema.$isSingleNested;
- }
- return ret;
- }
- }
- } else if (foundschema.$isSchemaMap) {
- if (p + 1 >= parts.length) {
- return foundschema.$__schemaType;
- }
- const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema);
- return ret;
- }
- foundschema.$fullPath = resultPath.join('.');
- return foundschema;
- }
- }
- }
-
- const parts = path.split('.');
- for (let i = 0; i < parts.length; ++i) {
- if (parts[i] === '$' || isArrayFilter(parts[i])) {
-
- parts[i] = '0';
- }
- }
- return search(parts, _this);
- };
- Schema.prototype._getPathType = function(path) {
- const _this = this;
- const pathschema = _this.path(path);
- if (pathschema) {
- return 'real';
- }
- function search(parts, schema) {
- let p = parts.length + 1,
- foundschema,
- trypath;
- while (p--) {
- trypath = parts.slice(0, p).join('.');
- foundschema = schema.path(trypath);
- if (foundschema) {
- if (foundschema.caster) {
-
- if (foundschema.caster instanceof MongooseTypes.Mixed) {
- return { schema: foundschema, pathType: 'mixed' };
- }
-
-
-
-
-
-
- if (p !== parts.length && foundschema.schema) {
- if (parts[p] === '$' || isArrayFilter(parts[p])) {
- if (p === parts.length - 1) {
- return { schema: foundschema, pathType: 'nested' };
- }
-
- return search(parts.slice(p + 1), foundschema.schema);
- }
-
- return search(parts.slice(p), foundschema.schema);
- }
- return {
- schema: foundschema,
- pathType: foundschema.$isSingleNested ? 'nested' : 'array'
- };
- }
- return { schema: foundschema, pathType: 'real' };
- } else if (p === parts.length && schema.nested[trypath]) {
- return { schema: schema, pathType: 'nested' };
- }
- }
- return { schema: foundschema || schema, pathType: 'undefined' };
- }
-
- return search(path.split('.'), _this);
- };
- function isArrayFilter(piece) {
- return piece.startsWith('$[') && piece.endsWith(']');
- }
- module.exports = exports = Schema;
- Schema.Types = MongooseTypes = require('./schema/index');
- exports.ObjectId = MongooseTypes.ObjectId;
|