schema.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const EventEmitter = require('events').EventEmitter;
  6. const Kareem = require('kareem');
  7. const MongooseError = require('./error/mongooseError');
  8. const SchemaType = require('./schematype');
  9. const SchemaTypeOptions = require('./options/SchemaTypeOptions');
  10. const VirtualOptions = require('./options/VirtualOptions');
  11. const VirtualType = require('./virtualtype');
  12. const addAutoId = require('./helpers/schema/addAutoId');
  13. const get = require('./helpers/get');
  14. const getConstructorName = require('./helpers/getConstructorName');
  15. const getIndexes = require('./helpers/schema/getIndexes');
  16. const idGetter = require('./helpers/schema/idGetter');
  17. const merge = require('./helpers/schema/merge');
  18. const mpath = require('mpath');
  19. const readPref = require('./driver').get().ReadPreference;
  20. const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
  21. const utils = require('./utils');
  22. const validateRef = require('./helpers/populate/validateRef');
  23. const util = require('util');
  24. let MongooseTypes;
  25. const queryHooks = require('./helpers/query/applyQueryMiddleware').
  26. middlewareFunctions;
  27. const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
  28. const hookNames = queryHooks.concat(documentHooks).
  29. reduce((s, hook) => s.add(hook), new Set());
  30. const isPOJO = utils.isPOJO;
  31. let id = 0;
  32. /**
  33. * Schema constructor.
  34. *
  35. * #### Example:
  36. *
  37. * const child = new Schema({ name: String });
  38. * const schema = new Schema({ name: String, age: Number, children: [child] });
  39. * const Tree = mongoose.model('Tree', schema);
  40. *
  41. * // setting schema options
  42. * new Schema({ name: String }, { _id: false, autoIndex: false })
  43. *
  44. * #### Options:
  45. *
  46. * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
  47. * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
  48. * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
  49. * - [bufferTimeoutMS](/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.
  50. * - [capped](/docs/guide.html#capped): bool | number | object - defaults to false
  51. * - [collection](/docs/guide.html#collection): string - no default
  52. * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t`
  53. * - [id](/docs/guide.html#id): bool - defaults to true
  54. * - [_id](/docs/guide.html#_id): bool - defaults to true
  55. * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
  56. * - [read](/docs/guide.html#read): string
  57. * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/)
  58. * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null`
  59. * - [strict](/docs/guide.html#strict): bool - defaults to true
  60. * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false
  61. * - [toJSON](/docs/guide.html#toJSON) - object - no default
  62. * - [toObject](/docs/guide.html#toObject) - object - no default
  63. * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
  64. * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
  65. * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v"
  66. * - [optimisticConcurrency](/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).
  67. * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
  68. * - [timeseries](/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection)
  69. * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
  70. * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
  71. * - [timestamps](/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.
  72. * - [pluginTags](/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.
  73. *
  74. * #### Options for Nested Schemas:
  75. * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths.
  76. *
  77. * #### Note:
  78. *
  79. * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
  80. *
  81. * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
  82. * @param {Object} [options]
  83. * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#events_class_events_eventemitter
  84. * @event `init`: Emitted after the schema is compiled into a `Model`.
  85. * @api public
  86. */
  87. function Schema(obj, options) {
  88. if (!(this instanceof Schema)) {
  89. return new Schema(obj, options);
  90. }
  91. this.obj = obj;
  92. this.paths = {};
  93. this.aliases = {};
  94. this.subpaths = {};
  95. this.virtuals = {};
  96. this.singleNestedPaths = {};
  97. this.nested = {};
  98. this.inherits = {};
  99. this.callQueue = [];
  100. this._indexes = [];
  101. this.methods = (options && options.methods) || {};
  102. this.methodOptions = {};
  103. this.statics = (options && options.statics) || {};
  104. this.tree = {};
  105. this.query = (options && options.query) || {};
  106. this.childSchemas = [];
  107. this.plugins = [];
  108. // For internal debugging. Do not use this to try to save a schema in MDB.
  109. this.$id = ++id;
  110. this.mapPaths = [];
  111. this.s = {
  112. hooks: new Kareem()
  113. };
  114. this.options = this.defaultOptions(options);
  115. // build paths
  116. if (Array.isArray(obj)) {
  117. for (const definition of obj) {
  118. this.add(definition);
  119. }
  120. } else if (obj) {
  121. this.add(obj);
  122. }
  123. // check if _id's value is a subdocument (gh-2276)
  124. const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
  125. // ensure the documents get an auto _id unless disabled
  126. const auto_id = !this.paths['_id'] &&
  127. (this.options._id) && !_idSubDoc;
  128. if (auto_id) {
  129. addAutoId(this);
  130. }
  131. this.setupTimestamp(this.options.timestamps);
  132. }
  133. /*!
  134. * Create virtual properties with alias field
  135. */
  136. function aliasFields(schema, paths) {
  137. paths = paths || Object.keys(schema.paths);
  138. for (const path of paths) {
  139. const options = get(schema.paths[path], 'options');
  140. if (options == null) {
  141. continue;
  142. }
  143. const prop = schema.paths[path].path;
  144. const alias = options.alias;
  145. if (!alias) {
  146. continue;
  147. }
  148. if (typeof alias !== 'string') {
  149. throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
  150. }
  151. schema.aliases[alias] = prop;
  152. schema.
  153. virtual(alias).
  154. get((function(p) {
  155. return function() {
  156. if (typeof this.get === 'function') {
  157. return this.get(p);
  158. }
  159. return this[p];
  160. };
  161. })(prop)).
  162. set((function(p) {
  163. return function(v) {
  164. return this.$set(p, v);
  165. };
  166. })(prop));
  167. }
  168. }
  169. /*!
  170. * Inherit from EventEmitter.
  171. */
  172. Schema.prototype = Object.create(EventEmitter.prototype);
  173. Schema.prototype.constructor = Schema;
  174. Schema.prototype.instanceOfSchema = true;
  175. /*!
  176. * ignore
  177. */
  178. Object.defineProperty(Schema.prototype, '$schemaType', {
  179. configurable: false,
  180. enumerable: false,
  181. writable: true
  182. });
  183. /**
  184. * Array of child schemas (from document arrays and single nested subdocs)
  185. * and their corresponding compiled models. Each element of the array is
  186. * an object with 2 properties: `schema` and `model`.
  187. *
  188. * This property is typically only useful for plugin authors and advanced users.
  189. * You do not need to interact with this property at all to use mongoose.
  190. *
  191. * @api public
  192. * @property childSchemas
  193. * @memberOf Schema
  194. * @instance
  195. */
  196. Object.defineProperty(Schema.prototype, 'childSchemas', {
  197. configurable: false,
  198. enumerable: true,
  199. writable: true
  200. });
  201. /**
  202. * Object containing all virtuals defined on this schema.
  203. * The objects' keys are the virtual paths and values are instances of `VirtualType`.
  204. *
  205. * This property is typically only useful for plugin authors and advanced users.
  206. * You do not need to interact with this property at all to use mongoose.
  207. *
  208. * #### Example:
  209. * const schema = new Schema({});
  210. * schema.virtual('answer').get(() => 42);
  211. *
  212. * console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
  213. * console.log(schema.virtuals['answer'].getters[0].call()); // 42
  214. *
  215. * @api public
  216. * @property virtuals
  217. * @memberOf Schema
  218. * @instance
  219. */
  220. Object.defineProperty(Schema.prototype, 'virtuals', {
  221. configurable: false,
  222. enumerable: true,
  223. writable: true
  224. });
  225. /**
  226. * The original object passed to the schema constructor
  227. *
  228. * #### Example:
  229. *
  230. * const schema = new Schema({ a: String }).add({ b: String });
  231. * schema.obj; // { a: String }
  232. *
  233. * @api public
  234. * @property obj
  235. * @memberOf Schema
  236. * @instance
  237. */
  238. Schema.prototype.obj;
  239. /**
  240. * The paths defined on this schema. The keys are the top-level paths
  241. * in this schema, and the values are instances of the SchemaType class.
  242. *
  243. * #### Example:
  244. * const schema = new Schema({ name: String }, { _id: false });
  245. * schema.paths; // { name: SchemaString { ... } }
  246. *
  247. * schema.add({ age: Number });
  248. * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
  249. *
  250. * @api public
  251. * @property paths
  252. * @memberOf Schema
  253. * @instance
  254. */
  255. Schema.prototype.paths;
  256. /**
  257. * Schema as a tree
  258. *
  259. * #### Example:
  260. * {
  261. * '_id' : ObjectId
  262. * , 'nested' : {
  263. * 'key' : String
  264. * }
  265. * }
  266. *
  267. * @api private
  268. * @property tree
  269. * @memberOf Schema
  270. * @instance
  271. */
  272. Schema.prototype.tree;
  273. /**
  274. * Returns a deep copy of the schema
  275. *
  276. * #### Example:
  277. *
  278. * const schema = new Schema({ name: String });
  279. * const clone = schema.clone();
  280. * clone === schema; // false
  281. * clone.path('name'); // SchemaString { ... }
  282. *
  283. * @return {Schema} the cloned schema
  284. * @api public
  285. * @memberOf Schema
  286. * @instance
  287. */
  288. Schema.prototype.clone = function() {
  289. const s = this._clone();
  290. // Bubble up `init` for backwards compat
  291. s.on('init', v => this.emit('init', v));
  292. return s;
  293. };
  294. /*!
  295. * ignore
  296. */
  297. Schema.prototype._clone = function _clone(Constructor) {
  298. Constructor = Constructor || (this.base == null ? Schema : this.base.Schema);
  299. const s = new Constructor({}, this._userProvidedOptions);
  300. s.base = this.base;
  301. s.obj = this.obj;
  302. s.options = utils.clone(this.options);
  303. s.callQueue = this.callQueue.map(function(f) { return f; });
  304. s.methods = utils.clone(this.methods);
  305. s.methodOptions = utils.clone(this.methodOptions);
  306. s.statics = utils.clone(this.statics);
  307. s.query = utils.clone(this.query);
  308. s.plugins = Array.prototype.slice.call(this.plugins);
  309. s._indexes = utils.clone(this._indexes);
  310. s.s.hooks = this.s.hooks.clone();
  311. s.tree = utils.clone(this.tree);
  312. s.paths = utils.clone(this.paths);
  313. s.nested = utils.clone(this.nested);
  314. s.subpaths = utils.clone(this.subpaths);
  315. s.singleNestedPaths = utils.clone(this.singleNestedPaths);
  316. s.childSchemas = gatherChildSchemas(s);
  317. s.virtuals = utils.clone(this.virtuals);
  318. s.$globalPluginsApplied = this.$globalPluginsApplied;
  319. s.$isRootDiscriminator = this.$isRootDiscriminator;
  320. s.$implicitlyCreated = this.$implicitlyCreated;
  321. s.$id = ++id;
  322. s.$originalSchemaId = this.$id;
  323. s.mapPaths = [].concat(this.mapPaths);
  324. if (this.discriminatorMapping != null) {
  325. s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
  326. }
  327. if (this.discriminators != null) {
  328. s.discriminators = Object.assign({}, this.discriminators);
  329. }
  330. if (this._applyDiscriminators != null) {
  331. s._applyDiscriminators = Object.assign({}, this._applyDiscriminators);
  332. }
  333. s.aliases = Object.assign({}, this.aliases);
  334. return s;
  335. };
  336. /**
  337. * Returns a new schema that has the picked `paths` from this schema.
  338. *
  339. * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas.
  340. *
  341. * #### Example:
  342. *
  343. * const schema = Schema({ name: String, age: Number });
  344. * // Creates a new schema with the same `name` path as `schema`,
  345. * // but no `age` path.
  346. * const newSchema = schema.pick(['name']);
  347. *
  348. * newSchema.path('name'); // SchemaString { ... }
  349. * newSchema.path('age'); // undefined
  350. *
  351. * @param {Array} paths list of paths to pick
  352. * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set.
  353. * @return {Schema}
  354. * @api public
  355. */
  356. Schema.prototype.pick = function(paths, options) {
  357. const newSchema = new Schema({}, options || this.options);
  358. if (!Array.isArray(paths)) {
  359. throw new MongooseError('Schema#pick() only accepts an array argument, ' +
  360. 'got "' + typeof paths + '"');
  361. }
  362. for (const path of paths) {
  363. if (this.nested[path]) {
  364. newSchema.add({ [path]: get(this.tree, path) });
  365. } else {
  366. const schematype = this.path(path);
  367. if (schematype == null) {
  368. throw new MongooseError('Path `' + path + '` is not in the schema');
  369. }
  370. newSchema.add({ [path]: schematype });
  371. }
  372. }
  373. return newSchema;
  374. };
  375. /**
  376. * Returns default options for this schema, merged with `options`.
  377. *
  378. * @param {Object} options
  379. * @return {Object}
  380. * @api private
  381. */
  382. Schema.prototype.defaultOptions = function(options) {
  383. this._userProvidedOptions = options == null ? {} : utils.clone(options);
  384. const baseOptions = this.base && this.base.options || {};
  385. const strict = 'strict' in baseOptions ? baseOptions.strict : true;
  386. options = utils.options({
  387. strict: strict,
  388. strictQuery: 'strict' in this._userProvidedOptions ?
  389. this._userProvidedOptions.strict :
  390. 'strictQuery' in baseOptions ?
  391. baseOptions.strictQuery : strict,
  392. bufferCommands: true,
  393. capped: false, // { size, max, autoIndexId }
  394. versionKey: '__v',
  395. optimisticConcurrency: false,
  396. minimize: true,
  397. autoIndex: null,
  398. discriminatorKey: '__t',
  399. shardKey: null,
  400. read: null,
  401. validateBeforeSave: true,
  402. // the following are only applied at construction time
  403. _id: true,
  404. id: true,
  405. typeKey: 'type'
  406. }, utils.clone(options));
  407. if (options.read) {
  408. options.read = readPref(options.read);
  409. }
  410. if (options.versionKey && typeof options.versionKey !== 'string') {
  411. throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`');
  412. }
  413. if (options.optimisticConcurrency && !options.versionKey) {
  414. throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
  415. }
  416. return options;
  417. };
  418. /**
  419. * Inherit a Schema by applying a discriminator on an existing Schema.
  420. *
  421. *
  422. * #### Example:
  423. *
  424. * const options = { discriminatorKey: 'kind' };
  425. *
  426. * const eventSchema = new mongoose.Schema({ time: Date }, options);
  427. * const Event = mongoose.model('Event', eventSchema);
  428. *
  429. * // ClickedLinkEvent is a special type of Event that has
  430. * // a URL.
  431. * const ClickedLinkEvent = Event.discriminator('ClickedLink',
  432. * new mongoose.Schema({ url: String }, options));
  433. *
  434. * // When you create a generic event, it can't have a URL field...
  435. * const genericEvent = new Event({ time: Date.now(), url: 'google.com' });
  436. * assert.ok(!genericEvent.url);
  437. * // But a ClickedLinkEvent can
  438. * const clickedEvent = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
  439. * assert.ok(clickedEvent.url);
  440. *
  441. * @param {String} name the name of the discriminator
  442. * @param {Schema} schema the Schema of the discriminated Schema
  443. * @return {Schema} the Schema instance
  444. * @api public
  445. */
  446. Schema.prototype.discriminator = function(name, schema) {
  447. this._applyDiscriminators = Object.assign(this._applyDiscriminators || {}, { [name]: schema });
  448. return this;
  449. };
  450. /**
  451. * Adds key path / schema type pairs to this schema.
  452. *
  453. * #### Example:
  454. *
  455. * const ToySchema = new Schema();
  456. * ToySchema.add({ name: 'string', color: 'string', price: 'number' });
  457. *
  458. * const TurboManSchema = new Schema();
  459. * // You can also `add()` another schema and copy over all paths, virtuals,
  460. * // getters, setters, indexes, methods, and statics.
  461. * TurboManSchema.add(ToySchema).add({ year: Number });
  462. *
  463. * @param {Object|Schema} obj plain object with paths to add, or another schema
  464. * @param {String} [prefix] path to prefix the newly added paths with
  465. * @return {Schema} the Schema instance
  466. * @api public
  467. */
  468. Schema.prototype.add = function add(obj, prefix) {
  469. if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
  470. merge(this, obj);
  471. return this;
  472. }
  473. // Special case: setting top-level `_id` to false should convert to disabling
  474. // the `_id` option. This behavior never worked before 5.4.11 but numerous
  475. // codebases use it (see gh-7516, gh-7512).
  476. if (obj._id === false && prefix == null) {
  477. this.options._id = false;
  478. }
  479. prefix = prefix || '';
  480. // avoid prototype pollution
  481. if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
  482. return this;
  483. }
  484. const keys = Object.keys(obj);
  485. const typeKey = this.options.typeKey;
  486. for (const key of keys) {
  487. const fullPath = prefix + key;
  488. const val = obj[key];
  489. if (val == null) {
  490. throw new TypeError('Invalid value for schema path `' + fullPath +
  491. '`, got value "' + val + '"');
  492. }
  493. // Retain `_id: false` but don't set it as a path, re: gh-8274.
  494. if (key === '_id' && val === false) {
  495. continue;
  496. }
  497. if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === 'VirtualType') {
  498. this.virtual(val);
  499. continue;
  500. }
  501. if (Array.isArray(val) && val.length === 1 && val[0] == null) {
  502. throw new TypeError('Invalid value for schema Array path `' + fullPath +
  503. '`, got value "' + val[0] + '"');
  504. }
  505. if (!(isPOJO(val) || val instanceof SchemaTypeOptions)) {
  506. // Special-case: Non-options definitely a path so leaf at this node
  507. // Examples: Schema instances, SchemaType instances
  508. if (prefix) {
  509. this.nested[prefix.substring(0, prefix.length - 1)] = true;
  510. }
  511. this.path(prefix + key, val);
  512. if (val[0] != null && !(val[0].instanceOfSchema) && utils.isPOJO(val[0].discriminators)) {
  513. const schemaType = this.path(prefix + key);
  514. for (const key in val[0].discriminators) {
  515. schemaType.discriminator(key, val[0].discriminators[key]);
  516. }
  517. } else if (val[0] != null && val[0].instanceOfSchema && utils.isPOJO(val[0]._applyDiscriminators)) {
  518. const applyDiscriminators = val[0]._applyDiscriminators || [];
  519. const schemaType = this.path(prefix + key);
  520. for (const disc in applyDiscriminators) {
  521. schemaType.discriminator(disc, applyDiscriminators[disc]);
  522. }
  523. }
  524. else if (val != null && val.instanceOfSchema && utils.isPOJO(val._applyDiscriminators)) {
  525. const applyDiscriminators = val._applyDiscriminators || [];
  526. const schemaType = this.path(prefix + key);
  527. for (const disc in applyDiscriminators) {
  528. schemaType.discriminator(disc, applyDiscriminators[disc]);
  529. }
  530. }
  531. } else if (Object.keys(val).length < 1) {
  532. // Special-case: {} always interpreted as Mixed path so leaf at this node
  533. if (prefix) {
  534. this.nested[prefix.substring(0, prefix.length - 1)] = true;
  535. }
  536. this.path(fullPath, val); // mixed type
  537. } else if (!val[typeKey] || (typeKey === 'type' && isPOJO(val.type) && val.type.type)) {
  538. // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse
  539. // nested object `{ last: { name: String } }`. Avoid functions with `.type` re: #10807 because
  540. // NestJS sometimes adds `Date.type`.
  541. this.nested[fullPath] = true;
  542. this.add(val, fullPath + '.');
  543. } else {
  544. // There IS a bona-fide type key that may also be a POJO
  545. const _typeDef = val[typeKey];
  546. if (isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) {
  547. // If a POJO is the value of a type key, make it a subdocument
  548. if (prefix) {
  549. this.nested[prefix.substring(0, prefix.length - 1)] = true;
  550. }
  551. const _schema = new Schema(_typeDef);
  552. const schemaWrappedPath = Object.assign({}, val, { type: _schema });
  553. this.path(prefix + key, schemaWrappedPath);
  554. } else {
  555. // Either the type is non-POJO or we interpret it as Mixed anyway
  556. if (prefix) {
  557. this.nested[prefix.substring(0, prefix.length - 1)] = true;
  558. }
  559. this.path(prefix + key, val);
  560. if (val != null && !(val.instanceOfSchema) && utils.isPOJO(val.discriminators)) {
  561. const schemaType = this.path(prefix + key);
  562. for (const key in val.discriminators) {
  563. schemaType.discriminator(key, val.discriminators[key]);
  564. }
  565. }
  566. }
  567. }
  568. }
  569. const addedKeys = Object.keys(obj).
  570. map(key => prefix ? prefix + key : key);
  571. aliasFields(this, addedKeys);
  572. return this;
  573. };
  574. /**
  575. * Remove an index by name or index specification.
  576. *
  577. * removeIndex only removes indexes from your schema object. Does **not** affect the indexes
  578. * in MongoDB.
  579. *
  580. * #### Example:
  581. *
  582. * const ToySchema = new Schema({ name: String, color: String, price: Number });
  583. *
  584. * // Add a new index on { name, color }
  585. * ToySchema.index({ name: 1, color: 1 });
  586. *
  587. * // Remove index on { name, color }
  588. * // Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index
  589. * ToySchema.removeIndex({ name: 1, color: 1 });
  590. *
  591. * // Add an index with a custom name
  592. * ToySchema.index({ color: 1 }, { name: 'my custom index name' });
  593. * // Remove index by name
  594. * ToySchema.removeIndex('my custom index name');
  595. *
  596. * @param {Object|string} index name or index specification
  597. * @return {Schema} the Schema instance
  598. * @api public
  599. */
  600. Schema.prototype.removeIndex = function removeIndex(index) {
  601. if (arguments.length > 1) {
  602. throw new Error('removeIndex() takes only 1 argument');
  603. }
  604. if (typeof index !== 'object' && typeof index !== 'string') {
  605. throw new Error('removeIndex() may only take either an object or a string as an argument');
  606. }
  607. if (typeof index === 'object') {
  608. for (let i = this._indexes.length - 1; i >= 0; --i) {
  609. if (util.isDeepStrictEqual(this._indexes[i][0], index)) {
  610. this._indexes.splice(i, 1);
  611. }
  612. }
  613. } else {
  614. for (let i = this._indexes.length - 1; i >= 0; --i) {
  615. if (this._indexes[i][1] != null && this._indexes[i][1].name === index) {
  616. this._indexes.splice(i, 1);
  617. }
  618. }
  619. }
  620. return this;
  621. };
  622. /**
  623. * Remove all indexes from this schema.
  624. *
  625. * clearIndexes only removes indexes from your schema object. Does **not** affect the indexes
  626. * in MongoDB.
  627. *
  628. * #### Example:
  629. *
  630. * const ToySchema = new Schema({ name: String, color: String, price: Number });
  631. * ToySchema.index({ name: 1 });
  632. * ToySchema.index({ color: 1 });
  633. *
  634. * // Remove all indexes on this schema
  635. * ToySchema.clearIndexes();
  636. *
  637. * ToySchema.indexes(); // []
  638. *
  639. * @return {Schema} the Schema instance
  640. * @api public
  641. */
  642. Schema.prototype.clearIndexes = function clearIndexes() {
  643. this._indexes.length = 0;
  644. return this;
  645. };
  646. /**
  647. * Reserved document keys.
  648. *
  649. * Keys in this object are names that are warned in schema declarations
  650. * because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema
  651. * using `new Schema()` with one of these property names, Mongoose will log a warning.
  652. *
  653. * - _posts
  654. * - _pres
  655. * - collection
  656. * - emit
  657. * - errors
  658. * - get
  659. * - init
  660. * - isModified
  661. * - isNew
  662. * - listeners
  663. * - modelName
  664. * - on
  665. * - once
  666. * - populated
  667. * - prototype
  668. * - remove
  669. * - removeListener
  670. * - save
  671. * - schema
  672. * - toObject
  673. * - validate
  674. *
  675. * _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.
  676. *
  677. * const schema = new Schema(..);
  678. * schema.methods.init = function () {} // potentially breaking
  679. */
  680. Schema.reserved = Object.create(null);
  681. Schema.prototype.reserved = Schema.reserved;
  682. const reserved = Schema.reserved;
  683. // Core object
  684. reserved['prototype'] =
  685. // EventEmitter
  686. reserved.emit =
  687. reserved.listeners =
  688. reserved.removeListener =
  689. // document properties and functions
  690. reserved.collection =
  691. reserved.errors =
  692. reserved.get =
  693. reserved.init =
  694. reserved.isModified =
  695. reserved.isNew =
  696. reserved.populated =
  697. reserved.remove =
  698. reserved.save =
  699. reserved.toObject =
  700. reserved.validate = 1;
  701. reserved.collection = 1;
  702. /**
  703. * Gets/sets schema paths.
  704. *
  705. * Sets a path (if arity 2)
  706. * Gets a path (if arity 1)
  707. *
  708. * #### Example
  709. *
  710. * schema.path('name') // returns a SchemaType
  711. * schema.path('name', Number) // changes the schemaType of `name` to Number
  712. *
  713. * @param {String} path
  714. * @param {Object} constructor
  715. * @api public
  716. */
  717. Schema.prototype.path = function(path, obj) {
  718. // Convert to '.$' to check subpaths re: gh-6405
  719. const cleanPath = _pathToPositionalSyntax(path);
  720. if (obj === undefined) {
  721. let schematype = _getPath(this, path, cleanPath);
  722. if (schematype != null) {
  723. return schematype;
  724. }
  725. // Look for maps
  726. const mapPath = getMapPath(this, path);
  727. if (mapPath != null) {
  728. return mapPath;
  729. }
  730. // Look if a parent of this path is mixed
  731. schematype = this.hasMixedParent(cleanPath);
  732. if (schematype != null) {
  733. return schematype;
  734. }
  735. // subpaths?
  736. return /\.\d+\.?.*$/.test(path)
  737. ? getPositionalPath(this, path)
  738. : undefined;
  739. }
  740. // some path names conflict with document methods
  741. const firstPieceOfPath = path.split('.')[0];
  742. if (reserved[firstPieceOfPath] && !this.options.supressReservedKeysWarning) {
  743. const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. ` +
  744. 'You are allowed to use it, but use at your own risk. ' +
  745. 'To disable this warning pass `supressReservedKeysWarning` as a schema option.';
  746. utils.warn(errorMessage);
  747. }
  748. if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
  749. validateRef(obj.ref, path);
  750. }
  751. // update the tree
  752. const subpaths = path.split(/\./);
  753. const last = subpaths.pop();
  754. let branch = this.tree;
  755. let fullPath = '';
  756. for (const sub of subpaths) {
  757. fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub;
  758. if (!branch[sub]) {
  759. this.nested[fullPath] = true;
  760. branch[sub] = {};
  761. }
  762. if (typeof branch[sub] !== 'object') {
  763. const msg = 'Cannot set nested path `' + path + '`. '
  764. + 'Parent path `'
  765. + fullPath
  766. + '` already set to type ' + branch[sub].name
  767. + '.';
  768. throw new Error(msg);
  769. }
  770. branch = branch[sub];
  771. }
  772. branch[last] = utils.clone(obj);
  773. this.paths[path] = this.interpretAsType(path, obj, this.options);
  774. const schemaType = this.paths[path];
  775. if (schemaType.$isSchemaMap) {
  776. // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
  777. // The '$' is to imply this path should never be stored in MongoDB so we
  778. // can easily build a regexp out of this path, and '*' to imply "any key."
  779. const mapPath = path + '.$*';
  780. this.paths[mapPath] = schemaType.$__schemaType;
  781. this.mapPaths.push(this.paths[mapPath]);
  782. }
  783. if (schemaType.$isSingleNested) {
  784. for (const key of Object.keys(schemaType.schema.paths)) {
  785. this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
  786. }
  787. for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
  788. this.singleNestedPaths[path + '.' + key] =
  789. schemaType.schema.singleNestedPaths[key];
  790. }
  791. for (const key of Object.keys(schemaType.schema.subpaths)) {
  792. this.singleNestedPaths[path + '.' + key] =
  793. schemaType.schema.subpaths[key];
  794. }
  795. for (const key of Object.keys(schemaType.schema.nested)) {
  796. this.singleNestedPaths[path + '.' + key] = 'nested';
  797. }
  798. Object.defineProperty(schemaType.schema, 'base', {
  799. configurable: true,
  800. enumerable: false,
  801. writable: false,
  802. value: this.base
  803. });
  804. schemaType.caster.base = this.base;
  805. this.childSchemas.push({
  806. schema: schemaType.schema,
  807. model: schemaType.caster
  808. });
  809. } else if (schemaType.$isMongooseDocumentArray) {
  810. Object.defineProperty(schemaType.schema, 'base', {
  811. configurable: true,
  812. enumerable: false,
  813. writable: false,
  814. value: this.base
  815. });
  816. schemaType.casterConstructor.base = this.base;
  817. this.childSchemas.push({
  818. schema: schemaType.schema,
  819. model: schemaType.casterConstructor
  820. });
  821. }
  822. if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) {
  823. let arrayPath = path;
  824. let _schemaType = schemaType;
  825. const toAdd = [];
  826. while (_schemaType.$isMongooseArray) {
  827. arrayPath = arrayPath + '.$';
  828. // Skip arrays of document arrays
  829. if (_schemaType.$isMongooseDocumentArray) {
  830. _schemaType.$embeddedSchemaType._arrayPath = arrayPath;
  831. _schemaType.$embeddedSchemaType._arrayParentPath = path;
  832. _schemaType = _schemaType.$embeddedSchemaType.clone();
  833. } else {
  834. _schemaType.caster._arrayPath = arrayPath;
  835. _schemaType.caster._arrayParentPath = path;
  836. _schemaType = _schemaType.caster.clone();
  837. }
  838. _schemaType.path = arrayPath;
  839. toAdd.push(_schemaType);
  840. }
  841. for (const _schemaType of toAdd) {
  842. this.subpaths[_schemaType.path] = _schemaType;
  843. }
  844. }
  845. if (schemaType.$isMongooseDocumentArray) {
  846. for (const key of Object.keys(schemaType.schema.paths)) {
  847. const _schemaType = schemaType.schema.paths[key];
  848. this.subpaths[path + '.' + key] = _schemaType;
  849. if (typeof _schemaType === 'object' && _schemaType != null) {
  850. _schemaType.$isUnderneathDocArray = true;
  851. }
  852. }
  853. for (const key of Object.keys(schemaType.schema.subpaths)) {
  854. const _schemaType = schemaType.schema.subpaths[key];
  855. this.subpaths[path + '.' + key] = _schemaType;
  856. if (typeof _schemaType === 'object' && _schemaType != null) {
  857. _schemaType.$isUnderneathDocArray = true;
  858. }
  859. }
  860. for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
  861. const _schemaType = schemaType.schema.singleNestedPaths[key];
  862. this.subpaths[path + '.' + key] = _schemaType;
  863. if (typeof _schemaType === 'object' && _schemaType != null) {
  864. _schemaType.$isUnderneathDocArray = true;
  865. }
  866. }
  867. }
  868. return this;
  869. };
  870. /*!
  871. * ignore
  872. */
  873. function gatherChildSchemas(schema) {
  874. const childSchemas = [];
  875. for (const path of Object.keys(schema.paths)) {
  876. const schematype = schema.paths[path];
  877. if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
  878. childSchemas.push({ schema: schematype.schema, model: schematype.caster });
  879. }
  880. }
  881. return childSchemas;
  882. }
  883. /*!
  884. * ignore
  885. */
  886. function _getPath(schema, path, cleanPath) {
  887. if (schema.paths.hasOwnProperty(path)) {
  888. return schema.paths[path];
  889. }
  890. if (schema.subpaths.hasOwnProperty(cleanPath)) {
  891. return schema.subpaths[cleanPath];
  892. }
  893. if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
  894. return schema.singleNestedPaths[cleanPath];
  895. }
  896. return null;
  897. }
  898. /*!
  899. * ignore
  900. */
  901. function _pathToPositionalSyntax(path) {
  902. if (!/\.\d+/.test(path)) {
  903. return path;
  904. }
  905. return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$');
  906. }
  907. /*!
  908. * ignore
  909. */
  910. function getMapPath(schema, path) {
  911. if (schema.mapPaths.length === 0) {
  912. return null;
  913. }
  914. for (const val of schema.mapPaths) {
  915. const _path = val.path;
  916. const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
  917. if (re.test(path)) {
  918. return schema.paths[_path];
  919. }
  920. }
  921. return null;
  922. }
  923. /**
  924. * The Mongoose instance this schema is associated with
  925. *
  926. * @property base
  927. * @api private
  928. */
  929. Object.defineProperty(Schema.prototype, 'base', {
  930. configurable: true,
  931. enumerable: false,
  932. writable: true,
  933. value: null
  934. });
  935. /**
  936. * Converts type arguments into Mongoose Types.
  937. *
  938. * @param {String} path
  939. * @param {Object} obj constructor
  940. * @api private
  941. */
  942. Schema.prototype.interpretAsType = function(path, obj, options) {
  943. if (obj instanceof SchemaType) {
  944. if (obj.path === path) {
  945. return obj;
  946. }
  947. const clone = obj.clone();
  948. clone.path = path;
  949. return clone;
  950. }
  951. // If this schema has an associated Mongoose object, use the Mongoose object's
  952. // copy of SchemaTypes re: gh-7158 gh-6933
  953. const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
  954. if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) {
  955. const constructorName = utils.getFunctionName(obj.constructor);
  956. if (constructorName !== 'Object') {
  957. const oldObj = obj;
  958. obj = {};
  959. obj[options.typeKey] = oldObj;
  960. }
  961. }
  962. // Get the type making sure to allow keys named "type"
  963. // and default to mixed if not specified.
  964. // { type: { type: String, default: 'freshcut' } }
  965. let type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== 'type' || !obj.type.type)
  966. ? obj[options.typeKey]
  967. : {};
  968. let name;
  969. if (utils.isPOJO(type) || type === 'mixed') {
  970. return new MongooseTypes.Mixed(path, obj);
  971. }
  972. if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) {
  973. // if it was specified through { type } look for `cast`
  974. let cast = (type === Array || type === 'array')
  975. ? obj.cast || obj.of
  976. : type[0];
  977. // new Schema({ path: [new Schema({ ... })] })
  978. if (cast && cast.instanceOfSchema) {
  979. if (!(cast instanceof Schema)) {
  980. throw new TypeError('Schema for array path `' + path +
  981. '` is from a different copy of the Mongoose module. ' +
  982. 'Please make sure you\'re using the same version ' +
  983. 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
  984. 'getting this error, please add `new Schema()` around the path: ' +
  985. `${path}: new Schema(...)`);
  986. }
  987. return new MongooseTypes.DocumentArray(path, cast, obj);
  988. }
  989. if (cast &&
  990. cast[options.typeKey] &&
  991. cast[options.typeKey].instanceOfSchema) {
  992. if (!(cast[options.typeKey] instanceof Schema)) {
  993. throw new TypeError('Schema for array path `' + path +
  994. '` is from a different copy of the Mongoose module. ' +
  995. 'Please make sure you\'re using the same version ' +
  996. 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
  997. 'getting this error, please add `new Schema()` around the path: ' +
  998. `${path}: new Schema(...)`);
  999. }
  1000. return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
  1001. }
  1002. if (Array.isArray(cast)) {
  1003. return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
  1004. }
  1005. // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })`
  1006. const castFromTypeKey = (cast != null && cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)) ?
  1007. cast[options.typeKey] :
  1008. cast;
  1009. if (typeof cast === 'string') {
  1010. cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
  1011. } else if (utils.isPOJO(castFromTypeKey)) {
  1012. if (Object.keys(castFromTypeKey).length) {
  1013. // The `minimize` and `typeKey` options propagate to child schemas
  1014. // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
  1015. // See gh-3560
  1016. const childSchemaOptions = { minimize: options.minimize };
  1017. if (options.typeKey) {
  1018. childSchemaOptions.typeKey = options.typeKey;
  1019. }
  1020. // propagate 'strict' option to child schema
  1021. if (options.hasOwnProperty('strict')) {
  1022. childSchemaOptions.strict = options.strict;
  1023. }
  1024. if (this._userProvidedOptions.hasOwnProperty('_id')) {
  1025. childSchemaOptions._id = this._userProvidedOptions._id;
  1026. } else if (Schema.Types.DocumentArray.defaultOptions._id != null) {
  1027. childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id;
  1028. }
  1029. const childSchema = new Schema(castFromTypeKey, childSchemaOptions);
  1030. childSchema.$implicitlyCreated = true;
  1031. return new MongooseTypes.DocumentArray(path, childSchema, obj);
  1032. } else {
  1033. // Special case: empty object becomes mixed
  1034. return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
  1035. }
  1036. }
  1037. if (cast) {
  1038. type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
  1039. ? cast[options.typeKey]
  1040. : cast;
  1041. if (Array.isArray(type)) {
  1042. return new MongooseTypes.Array(path, this.interpretAsType(path, type, options), obj);
  1043. }
  1044. name = typeof type === 'string'
  1045. ? type
  1046. : type.schemaName || utils.getFunctionName(type);
  1047. // For Jest 26+, see #10296
  1048. if (name === 'ClockDate') {
  1049. name = 'Date';
  1050. }
  1051. if (name === void 0) {
  1052. throw new TypeError('Invalid schema configuration: ' +
  1053. `Could not determine the embedded type for array \`${path}\`. ` +
  1054. 'See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
  1055. }
  1056. if (!MongooseTypes.hasOwnProperty(name)) {
  1057. throw new TypeError('Invalid schema configuration: ' +
  1058. `\`${name}\` is not a valid type within the array \`${path}\`.` +
  1059. 'See https://bit.ly/mongoose-schematypes for a list of valid schema types.');
  1060. }
  1061. }
  1062. return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
  1063. }
  1064. if (type && type.instanceOfSchema) {
  1065. return new MongooseTypes.Subdocument(type, path, obj);
  1066. }
  1067. if (Buffer.isBuffer(type)) {
  1068. name = 'Buffer';
  1069. } else if (typeof type === 'function' || typeof type === 'object') {
  1070. name = type.schemaName || utils.getFunctionName(type);
  1071. } else {
  1072. name = type == null ? '' + type : type.toString();
  1073. }
  1074. if (name) {
  1075. name = name.charAt(0).toUpperCase() + name.substring(1);
  1076. }
  1077. // Special case re: gh-7049 because the bson `ObjectID` class' capitalization
  1078. // doesn't line up with Mongoose's.
  1079. if (name === 'ObjectID') {
  1080. name = 'ObjectId';
  1081. }
  1082. // For Jest 26+, see #10296
  1083. if (name === 'ClockDate') {
  1084. name = 'Date';
  1085. }
  1086. if (name === void 0) {
  1087. throw new TypeError(`Invalid schema configuration: \`${path}\` schematype definition is ` +
  1088. 'invalid. See ' +
  1089. 'https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
  1090. }
  1091. if (MongooseTypes[name] == null) {
  1092. throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
  1093. `a valid type at path \`${path}\`. See ` +
  1094. 'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
  1095. }
  1096. const schemaType = new MongooseTypes[name](path, obj);
  1097. if (schemaType.$isSchemaMap) {
  1098. createMapNestedSchemaType(this, schemaType, path, obj, options);
  1099. }
  1100. return schemaType;
  1101. };
  1102. /*!
  1103. * ignore
  1104. */
  1105. function createMapNestedSchemaType(schema, schemaType, path, obj, options) {
  1106. const mapPath = path + '.$*';
  1107. let _mapType = { type: {} };
  1108. if (utils.hasUserDefinedProperty(obj, 'of')) {
  1109. const isInlineSchema = utils.isPOJO(obj.of) &&
  1110. Object.keys(obj.of).length > 0 &&
  1111. !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey);
  1112. if (isInlineSchema) {
  1113. _mapType = { [schema.options.typeKey]: new Schema(obj.of) };
  1114. } else if (utils.isPOJO(obj.of)) {
  1115. _mapType = Object.assign({}, obj.of);
  1116. } else {
  1117. _mapType = { [schema.options.typeKey]: obj.of };
  1118. }
  1119. if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) {
  1120. const subdocumentSchema = _mapType[schema.options.typeKey];
  1121. subdocumentSchema.eachPath((subpath, type) => {
  1122. if (type.options.select === true || type.options.select === false) {
  1123. throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + '.' + subpath + '"');
  1124. }
  1125. });
  1126. }
  1127. if (utils.hasUserDefinedProperty(obj, 'ref')) {
  1128. _mapType.ref = obj.ref;
  1129. }
  1130. }
  1131. schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options);
  1132. }
  1133. /**
  1134. * Iterates the schemas paths similar to Array#forEach.
  1135. *
  1136. * The callback is passed the pathname and the schemaType instance.
  1137. *
  1138. * #### Example:
  1139. *
  1140. * const userSchema = new Schema({ name: String, registeredAt: Date });
  1141. * userSchema.eachPath((pathname, schematype) => {
  1142. * // Prints twice:
  1143. * // name SchemaString { ... }
  1144. * // registeredAt SchemaDate { ... }
  1145. * console.log(pathname, schematype);
  1146. * });
  1147. *
  1148. * @param {Function} fn callback function
  1149. * @return {Schema} this
  1150. * @api public
  1151. */
  1152. Schema.prototype.eachPath = function(fn) {
  1153. const keys = Object.keys(this.paths);
  1154. const len = keys.length;
  1155. for (let i = 0; i < len; ++i) {
  1156. fn(keys[i], this.paths[keys[i]]);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Returns an Array of path strings that are required by this schema.
  1162. *
  1163. * #### Example:
  1164. * const s = new Schema({
  1165. * name: { type: String, required: true },
  1166. * age: { type: String, required: true },
  1167. * notes: String
  1168. * });
  1169. * s.requiredPaths(); // [ 'age', 'name' ]
  1170. *
  1171. * @api public
  1172. * @param {Boolean} invalidate refresh the cache
  1173. * @return {Array}
  1174. */
  1175. Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
  1176. if (this._requiredpaths && !invalidate) {
  1177. return this._requiredpaths;
  1178. }
  1179. const paths = Object.keys(this.paths);
  1180. let i = paths.length;
  1181. const ret = [];
  1182. while (i--) {
  1183. const path = paths[i];
  1184. if (this.paths[path].isRequired) {
  1185. ret.push(path);
  1186. }
  1187. }
  1188. this._requiredpaths = ret;
  1189. return this._requiredpaths;
  1190. };
  1191. /**
  1192. * Returns indexes from fields and schema-level indexes (cached).
  1193. *
  1194. * @api private
  1195. * @return {Array}
  1196. */
  1197. Schema.prototype.indexedPaths = function indexedPaths() {
  1198. if (this._indexedpaths) {
  1199. return this._indexedpaths;
  1200. }
  1201. this._indexedpaths = this.indexes();
  1202. return this._indexedpaths;
  1203. };
  1204. /**
  1205. * Returns the pathType of `path` for this schema.
  1206. *
  1207. * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
  1208. *
  1209. * #### Example:
  1210. * const s = new Schema({ name: String, nested: { foo: String } });
  1211. * s.virtual('foo').get(() => 42);
  1212. * s.pathType('name'); // "real"
  1213. * s.pathType('nested'); // "nested"
  1214. * s.pathType('foo'); // "virtual"
  1215. * s.pathType('fail'); // "adhocOrUndefined"
  1216. *
  1217. * @param {String} path
  1218. * @return {String}
  1219. * @api public
  1220. */
  1221. Schema.prototype.pathType = function(path) {
  1222. // Convert to '.$' to check subpaths re: gh-6405
  1223. const cleanPath = _pathToPositionalSyntax(path);
  1224. if (this.paths.hasOwnProperty(path)) {
  1225. return 'real';
  1226. }
  1227. if (this.virtuals.hasOwnProperty(path)) {
  1228. return 'virtual';
  1229. }
  1230. if (this.nested.hasOwnProperty(path)) {
  1231. return 'nested';
  1232. }
  1233. if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
  1234. return 'real';
  1235. }
  1236. const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path);
  1237. if (singleNestedPath) {
  1238. return singleNestedPath === 'nested' ? 'nested' : 'real';
  1239. }
  1240. // Look for maps
  1241. const mapPath = getMapPath(this, path);
  1242. if (mapPath != null) {
  1243. return 'real';
  1244. }
  1245. if (/\.\d+\.|\.\d+$/.test(path)) {
  1246. return getPositionalPathType(this, path);
  1247. }
  1248. return 'adhocOrUndefined';
  1249. };
  1250. /**
  1251. * Returns true iff this path is a child of a mixed schema.
  1252. *
  1253. * @param {String} path
  1254. * @return {Boolean}
  1255. * @api private
  1256. */
  1257. Schema.prototype.hasMixedParent = function(path) {
  1258. const subpaths = path.split(/\./g);
  1259. path = '';
  1260. for (let i = 0; i < subpaths.length; ++i) {
  1261. path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
  1262. if (this.paths.hasOwnProperty(path) &&
  1263. this.paths[path] instanceof MongooseTypes.Mixed) {
  1264. return this.paths[path];
  1265. }
  1266. }
  1267. return null;
  1268. };
  1269. /**
  1270. * Setup updatedAt and createdAt timestamps to documents if enabled
  1271. *
  1272. * @param {Boolean|Object} timestamps timestamps options
  1273. * @api private
  1274. */
  1275. Schema.prototype.setupTimestamp = function(timestamps) {
  1276. return setupTimestamps(this, timestamps);
  1277. };
  1278. /*!
  1279. * ignore. Deprecated re: #6405
  1280. */
  1281. function getPositionalPathType(self, path) {
  1282. const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
  1283. if (subpaths.length < 2) {
  1284. return self.paths.hasOwnProperty(subpaths[0]) ?
  1285. self.paths[subpaths[0]] :
  1286. 'adhocOrUndefined';
  1287. }
  1288. let val = self.path(subpaths[0]);
  1289. let isNested = false;
  1290. if (!val) {
  1291. return 'adhocOrUndefined';
  1292. }
  1293. const last = subpaths.length - 1;
  1294. for (let i = 1; i < subpaths.length; ++i) {
  1295. isNested = false;
  1296. const subpath = subpaths[i];
  1297. if (i === last && val && !/\D/.test(subpath)) {
  1298. if (val.$isMongooseDocumentArray) {
  1299. val = val.$embeddedSchemaType;
  1300. } else if (val instanceof MongooseTypes.Array) {
  1301. // StringSchema, NumberSchema, etc
  1302. val = val.caster;
  1303. } else {
  1304. val = undefined;
  1305. }
  1306. break;
  1307. }
  1308. // ignore if its just a position segment: path.0.subpath
  1309. if (!/\D/.test(subpath)) {
  1310. // Nested array
  1311. if (val instanceof MongooseTypes.Array && i !== last) {
  1312. val = val.caster;
  1313. }
  1314. continue;
  1315. }
  1316. if (!(val && val.schema)) {
  1317. val = undefined;
  1318. break;
  1319. }
  1320. const type = val.schema.pathType(subpath);
  1321. isNested = (type === 'nested');
  1322. val = val.schema.path(subpath);
  1323. }
  1324. self.subpaths[path] = val;
  1325. if (val) {
  1326. return 'real';
  1327. }
  1328. if (isNested) {
  1329. return 'nested';
  1330. }
  1331. return 'adhocOrUndefined';
  1332. }
  1333. /*!
  1334. * ignore
  1335. */
  1336. function getPositionalPath(self, path) {
  1337. getPositionalPathType(self, path);
  1338. return self.subpaths[path];
  1339. }
  1340. /**
  1341. * Adds a method call to the queue.
  1342. *
  1343. * #### Example:
  1344. *
  1345. * schema.methods.print = function() { console.log(this); };
  1346. * schema.queue('print', []); // Print the doc every one is instantiated
  1347. *
  1348. * const Model = mongoose.model('Test', schema);
  1349. * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
  1350. *
  1351. * @param {String} name name of the document method to call later
  1352. * @param {Array} args arguments to pass to the method
  1353. * @api public
  1354. */
  1355. Schema.prototype.queue = function(name, args) {
  1356. this.callQueue.push([name, args]);
  1357. return this;
  1358. };
  1359. /**
  1360. * Defines a pre hook for the model.
  1361. *
  1362. * #### Example
  1363. *
  1364. * const toySchema = new Schema({ name: String, created: Date });
  1365. *
  1366. * toySchema.pre('save', function(next) {
  1367. * if (!this.created) this.created = new Date;
  1368. * next();
  1369. * });
  1370. *
  1371. * toySchema.pre('validate', function(next) {
  1372. * if (this.name !== 'Woody') this.name = 'Woody';
  1373. * next();
  1374. * });
  1375. *
  1376. * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
  1377. * toySchema.pre(/^find/, function(next) {
  1378. * console.log(this.getFilter());
  1379. * });
  1380. *
  1381. * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
  1382. * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
  1383. * console.log(this.getFilter());
  1384. * });
  1385. *
  1386. * toySchema.pre('deleteOne', function() {
  1387. * // Runs when you call `Toy.deleteOne()`
  1388. * });
  1389. *
  1390. * toySchema.pre('deleteOne', { document: true }, function() {
  1391. * // Runs when you call `doc.deleteOne()`
  1392. * });
  1393. *
  1394. * @param {String|RegExp} The method name or regular expression to match method name
  1395. * @param {Object} [options]
  1396. * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`.
  1397. * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
  1398. * @param {Function} callback
  1399. * @api public
  1400. */
  1401. Schema.prototype.pre = function(name) {
  1402. if (name instanceof RegExp) {
  1403. const remainingArgs = Array.prototype.slice.call(arguments, 1);
  1404. for (const fn of hookNames) {
  1405. if (name.test(fn)) {
  1406. this.pre.apply(this, [fn].concat(remainingArgs));
  1407. }
  1408. }
  1409. return this;
  1410. }
  1411. if (Array.isArray(name)) {
  1412. const remainingArgs = Array.prototype.slice.call(arguments, 1);
  1413. for (const el of name) {
  1414. this.pre.apply(this, [el].concat(remainingArgs));
  1415. }
  1416. return this;
  1417. }
  1418. this.s.hooks.pre.apply(this.s.hooks, arguments);
  1419. return this;
  1420. };
  1421. /**
  1422. * Defines a post hook for the document
  1423. *
  1424. * const schema = new Schema(..);
  1425. * schema.post('save', function (doc) {
  1426. * console.log('this fired after a document was saved');
  1427. * });
  1428. *
  1429. * schema.post('find', function(docs) {
  1430. * console.log('this fired after you ran a find query');
  1431. * });
  1432. *
  1433. * schema.post(/Many$/, function(res) {
  1434. * console.log('this fired after you ran `updateMany()` or `deleteMany()`');
  1435. * });
  1436. *
  1437. * const Model = mongoose.model('Model', schema);
  1438. *
  1439. * const m = new Model(..);
  1440. * m.save(function(err) {
  1441. * console.log('this fires after the `post` hook');
  1442. * });
  1443. *
  1444. * m.find(function(err, docs) {
  1445. * console.log('this fires after the post find hook');
  1446. * });
  1447. *
  1448. * @param {String|RegExp} The method name or regular expression to match method name
  1449. * @param {Object} [options]
  1450. * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
  1451. * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
  1452. * @param {Function} fn callback
  1453. * @see middleware https://mongoosejs.com/docs/middleware.html
  1454. * @see kareem https://npmjs.org/package/kareem
  1455. * @api public
  1456. */
  1457. Schema.prototype.post = function(name) {
  1458. if (name instanceof RegExp) {
  1459. const remainingArgs = Array.prototype.slice.call(arguments, 1);
  1460. for (const fn of hookNames) {
  1461. if (name.test(fn)) {
  1462. this.post.apply(this, [fn].concat(remainingArgs));
  1463. }
  1464. }
  1465. return this;
  1466. }
  1467. if (Array.isArray(name)) {
  1468. const remainingArgs = Array.prototype.slice.call(arguments, 1);
  1469. for (const el of name) {
  1470. this.post.apply(this, [el].concat(remainingArgs));
  1471. }
  1472. return this;
  1473. }
  1474. this.s.hooks.post.apply(this.s.hooks, arguments);
  1475. return this;
  1476. };
  1477. /**
  1478. * Registers a plugin for this schema.
  1479. *
  1480. * #### Example:
  1481. *
  1482. * const s = new Schema({ name: String });
  1483. * s.plugin(schema => console.log(schema.path('name').path));
  1484. * mongoose.model('Test', s); // Prints 'name'
  1485. *
  1486. * @param {Function} plugin callback
  1487. * @param {Object} [opts]
  1488. * @see plugins
  1489. * @api public
  1490. */
  1491. Schema.prototype.plugin = function(fn, opts) {
  1492. if (typeof fn !== 'function') {
  1493. throw new Error('First param to `schema.plugin()` must be a function, ' +
  1494. 'got "' + (typeof fn) + '"');
  1495. }
  1496. if (opts && opts.deduplicate) {
  1497. for (const plugin of this.plugins) {
  1498. if (plugin.fn === fn) {
  1499. return this;
  1500. }
  1501. }
  1502. }
  1503. this.plugins.push({ fn: fn, opts: opts });
  1504. fn(this, opts);
  1505. return this;
  1506. };
  1507. /**
  1508. * Adds an instance method to documents constructed from Models compiled from this schema.
  1509. *
  1510. * #### Example
  1511. *
  1512. * const schema = kittySchema = new Schema(..);
  1513. *
  1514. * schema.method('meow', function () {
  1515. * console.log('meeeeeoooooooooooow');
  1516. * })
  1517. *
  1518. * const Kitty = mongoose.model('Kitty', schema);
  1519. *
  1520. * const fizz = new Kitty;
  1521. * fizz.meow(); // meeeeeooooooooooooow
  1522. *
  1523. * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
  1524. *
  1525. * schema.method({
  1526. * purr: function () {}
  1527. * , scratch: function () {}
  1528. * });
  1529. *
  1530. * // later
  1531. * fizz.purr();
  1532. * fizz.scratch();
  1533. *
  1534. * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods)
  1535. *
  1536. * @param {String|Object} method name
  1537. * @param {Function} [fn]
  1538. * @api public
  1539. */
  1540. Schema.prototype.method = function(name, fn, options) {
  1541. if (typeof name !== 'string') {
  1542. for (const i in name) {
  1543. this.methods[i] = name[i];
  1544. this.methodOptions[i] = utils.clone(options);
  1545. }
  1546. } else {
  1547. this.methods[name] = fn;
  1548. this.methodOptions[name] = utils.clone(options);
  1549. }
  1550. return this;
  1551. };
  1552. /**
  1553. * Adds static "class" methods to Models compiled from this schema.
  1554. *
  1555. * #### Example
  1556. *
  1557. * const schema = new Schema(..);
  1558. * // Equivalent to `schema.statics.findByName = function(name) {}`;
  1559. * schema.static('findByName', function(name) {
  1560. * return this.find({ name: name });
  1561. * });
  1562. *
  1563. * const Drink = mongoose.model('Drink', schema);
  1564. * await Drink.findByName('LaCroix');
  1565. *
  1566. * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
  1567. *
  1568. * @param {String|Object} name
  1569. * @param {Function} [fn]
  1570. * @api public
  1571. * @see Statics /docs/guide.html#statics
  1572. */
  1573. Schema.prototype.static = function(name, fn) {
  1574. if (typeof name !== 'string') {
  1575. for (const i in name) {
  1576. this.statics[i] = name[i];
  1577. }
  1578. } else {
  1579. this.statics[name] = fn;
  1580. }
  1581. return this;
  1582. };
  1583. /**
  1584. * Defines an index (most likely compound) for this schema.
  1585. *
  1586. * #### Example
  1587. *
  1588. * schema.index({ first: 1, last: -1 })
  1589. *
  1590. * @param {Object} fields
  1591. * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](https://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
  1592. * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
  1593. * @api public
  1594. */
  1595. Schema.prototype.index = function(fields, options) {
  1596. fields || (fields = {});
  1597. options || (options = {});
  1598. if (options.expires) {
  1599. utils.expires(options);
  1600. }
  1601. this._indexes.push([fields, options]);
  1602. return this;
  1603. };
  1604. /**
  1605. * Sets a schema option.
  1606. *
  1607. * #### Example
  1608. *
  1609. * schema.set('strict'); // 'true' by default
  1610. * schema.set('strict', false); // Sets 'strict' to false
  1611. * schema.set('strict'); // 'false'
  1612. *
  1613. * @param {String} key option name
  1614. * @param {Object} [value] if not passed, the current option value is returned
  1615. * @see Schema ./
  1616. * @api public
  1617. */
  1618. Schema.prototype.set = function(key, value, _tags) {
  1619. if (arguments.length === 1) {
  1620. return this.options[key];
  1621. }
  1622. switch (key) {
  1623. case 'read':
  1624. this.options[key] = readPref(value, _tags);
  1625. this._userProvidedOptions[key] = this.options[key];
  1626. break;
  1627. case 'timestamps':
  1628. this.setupTimestamp(value);
  1629. this.options[key] = value;
  1630. this._userProvidedOptions[key] = this.options[key];
  1631. break;
  1632. case '_id':
  1633. this.options[key] = value;
  1634. this._userProvidedOptions[key] = this.options[key];
  1635. if (value && !this.paths['_id']) {
  1636. addAutoId(this);
  1637. } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) {
  1638. this.remove('_id');
  1639. }
  1640. break;
  1641. default:
  1642. this.options[key] = value;
  1643. this._userProvidedOptions[key] = this.options[key];
  1644. break;
  1645. }
  1646. return this;
  1647. };
  1648. /**
  1649. * Gets a schema option.
  1650. *
  1651. * #### Example:
  1652. *
  1653. * schema.get('strict'); // true
  1654. * schema.set('strict', false);
  1655. * schema.get('strict'); // false
  1656. *
  1657. * @param {String} key option name
  1658. * @api public
  1659. * @return {Any} the option's value
  1660. */
  1661. Schema.prototype.get = function(key) {
  1662. return this.options[key];
  1663. };
  1664. /**
  1665. * The allowed index types
  1666. *
  1667. * @receiver Schema
  1668. * @static indexTypes
  1669. * @api public
  1670. */
  1671. const indexTypes = '2d 2dsphere hashed text'.split(' ');
  1672. Object.defineProperty(Schema, 'indexTypes', {
  1673. get: function() {
  1674. return indexTypes;
  1675. },
  1676. set: function() {
  1677. throw new Error('Cannot overwrite Schema.indexTypes');
  1678. }
  1679. });
  1680. /**
  1681. * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
  1682. * Indexes are expressed as an array `[spec, options]`.
  1683. *
  1684. * #### Example:
  1685. *
  1686. * const userSchema = new Schema({
  1687. * email: { type: String, required: true, unique: true },
  1688. * registeredAt: { type: Date, index: true }
  1689. * });
  1690. *
  1691. * // [ [ { email: 1 }, { unique: true, background: true } ],
  1692. * // [ { registeredAt: 1 }, { background: true } ] ]
  1693. * userSchema.indexes();
  1694. *
  1695. * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
  1696. * For example, the below plugin makes every index unique by default.
  1697. *
  1698. * function myPlugin(schema) {
  1699. * for (const index of schema.indexes()) {
  1700. * if (index[1].unique === undefined) {
  1701. * index[1].unique = true;
  1702. * }
  1703. * }
  1704. * }
  1705. *
  1706. * @api public
  1707. * @return {Array} list of indexes defined in the schema
  1708. */
  1709. Schema.prototype.indexes = function() {
  1710. return getIndexes(this);
  1711. };
  1712. /**
  1713. * Creates a virtual type with the given name.
  1714. *
  1715. * @param {String} name
  1716. * @param {Object} [options]
  1717. * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](/docs/populate.html#populate-virtuals).
  1718. * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information.
  1719. * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information.
  1720. * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
  1721. * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
  1722. * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc.
  1723. * @return {VirtualType}
  1724. */
  1725. Schema.prototype.virtual = function(name, options) {
  1726. if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
  1727. return this.virtual(name.path, name.options);
  1728. }
  1729. options = new VirtualOptions(options);
  1730. if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
  1731. if (options.localField == null) {
  1732. throw new Error('Reference virtuals require `localField` option');
  1733. }
  1734. if (options.foreignField == null) {
  1735. throw new Error('Reference virtuals require `foreignField` option');
  1736. }
  1737. this.pre('init', function(obj) {
  1738. if (mpath.has(name, obj)) {
  1739. const _v = mpath.get(name, obj);
  1740. if (!this.$$populatedVirtuals) {
  1741. this.$$populatedVirtuals = {};
  1742. }
  1743. if (options.justOne || options.count) {
  1744. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
  1745. _v[0] :
  1746. _v;
  1747. } else {
  1748. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
  1749. _v :
  1750. _v == null ? [] : [_v];
  1751. }
  1752. mpath.unset(name, obj);
  1753. }
  1754. });
  1755. const virtual = this.virtual(name);
  1756. virtual.options = options;
  1757. virtual.
  1758. set(function(_v) {
  1759. if (!this.$$populatedVirtuals) {
  1760. this.$$populatedVirtuals = {};
  1761. }
  1762. if (options.justOne || options.count) {
  1763. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
  1764. _v[0] :
  1765. _v;
  1766. if (typeof this.$$populatedVirtuals[name] !== 'object') {
  1767. this.$$populatedVirtuals[name] = options.count ? _v : null;
  1768. }
  1769. } else {
  1770. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
  1771. _v :
  1772. _v == null ? [] : [_v];
  1773. this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
  1774. return doc && typeof doc === 'object';
  1775. });
  1776. }
  1777. });
  1778. if (typeof options.get === 'function') {
  1779. virtual.get(options.get);
  1780. }
  1781. // Workaround for gh-8198: if virtual is under document array, make a fake
  1782. // virtual. See gh-8210
  1783. const parts = name.split('.');
  1784. let cur = parts[0];
  1785. for (let i = 0; i < parts.length - 1; ++i) {
  1786. if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) {
  1787. const remnant = parts.slice(i + 1).join('.');
  1788. this.paths[cur].schema.virtual(remnant, options);
  1789. break;
  1790. }
  1791. cur += '.' + parts[i + 1];
  1792. }
  1793. return virtual;
  1794. }
  1795. const virtuals = this.virtuals;
  1796. const parts = name.split('.');
  1797. if (this.pathType(name) === 'real') {
  1798. throw new Error('Virtual path "' + name + '"' +
  1799. ' conflicts with a real path in the schema');
  1800. }
  1801. virtuals[name] = parts.reduce(function(mem, part, i) {
  1802. mem[part] || (mem[part] = (i === parts.length - 1)
  1803. ? new VirtualType(options, name)
  1804. : {});
  1805. return mem[part];
  1806. }, this.tree);
  1807. return virtuals[name];
  1808. };
  1809. /**
  1810. * Returns the virtual type with the given `name`.
  1811. *
  1812. * @param {String} name
  1813. * @return {VirtualType}
  1814. */
  1815. Schema.prototype.virtualpath = function(name) {
  1816. return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
  1817. };
  1818. /**
  1819. * Removes the given `path` (or [`paths`]).
  1820. *
  1821. * #### Example:
  1822. *
  1823. * const schema = new Schema({ name: String, age: Number });
  1824. * schema.remove('name');
  1825. * schema.path('name'); // Undefined
  1826. * schema.path('age'); // SchemaNumber { ... }
  1827. *
  1828. * @param {String|Array} path
  1829. * @return {Schema} the Schema instance
  1830. * @api public
  1831. */
  1832. Schema.prototype.remove = function(path) {
  1833. if (typeof path === 'string') {
  1834. path = [path];
  1835. }
  1836. if (Array.isArray(path)) {
  1837. path.forEach(function(name) {
  1838. if (this.path(name) == null && !this.nested[name]) {
  1839. return;
  1840. }
  1841. if (this.nested[name]) {
  1842. const allKeys = Object.keys(this.paths).
  1843. concat(Object.keys(this.nested));
  1844. for (const path of allKeys) {
  1845. if (path.startsWith(name + '.')) {
  1846. delete this.paths[path];
  1847. delete this.nested[path];
  1848. _deletePath(this, path);
  1849. }
  1850. }
  1851. delete this.nested[name];
  1852. _deletePath(this, name);
  1853. return;
  1854. }
  1855. delete this.paths[name];
  1856. _deletePath(this, name);
  1857. }, this);
  1858. }
  1859. return this;
  1860. };
  1861. /*!
  1862. * ignore
  1863. */
  1864. function _deletePath(schema, name) {
  1865. const pieces = name.split('.');
  1866. const last = pieces.pop();
  1867. let branch = schema.tree;
  1868. for (const piece of pieces) {
  1869. branch = branch[piece];
  1870. }
  1871. delete branch[last];
  1872. }
  1873. /**
  1874. * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
  1875. * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
  1876. * to schema [virtuals](/docs/guide.html#virtuals),
  1877. * [statics](/docs/guide.html#statics), and
  1878. * [methods](/docs/guide.html#methods).
  1879. *
  1880. * #### Example:
  1881. *
  1882. * ```javascript
  1883. * const md5 = require('md5');
  1884. * const userSchema = new Schema({ email: String });
  1885. * class UserClass {
  1886. * // `gravatarImage` becomes a virtual
  1887. * get gravatarImage() {
  1888. * const hash = md5(this.email.toLowerCase());
  1889. * return `https://www.gravatar.com/avatar/${hash}`;
  1890. * }
  1891. *
  1892. * // `getProfileUrl()` becomes a document method
  1893. * getProfileUrl() {
  1894. * return `https://mysite.com/${this.email}`;
  1895. * }
  1896. *
  1897. * // `findByEmail()` becomes a static
  1898. * static findByEmail(email) {
  1899. * return this.findOne({ email });
  1900. * }
  1901. * }
  1902. *
  1903. * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
  1904. * // and a `findByEmail()` static
  1905. * userSchema.loadClass(UserClass);
  1906. * ```
  1907. *
  1908. * @param {Function} model
  1909. * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
  1910. */
  1911. Schema.prototype.loadClass = function(model, virtualsOnly) {
  1912. if (model === Object.prototype ||
  1913. model === Function.prototype ||
  1914. model.prototype.hasOwnProperty('$isMongooseModelPrototype')) {
  1915. return this;
  1916. }
  1917. this.loadClass(Object.getPrototypeOf(model), virtualsOnly);
  1918. // Add static methods
  1919. if (!virtualsOnly) {
  1920. Object.getOwnPropertyNames(model).forEach(function(name) {
  1921. if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) {
  1922. return;
  1923. }
  1924. const prop = Object.getOwnPropertyDescriptor(model, name);
  1925. if (prop.hasOwnProperty('value')) {
  1926. this.static(name, prop.value);
  1927. }
  1928. }, this);
  1929. }
  1930. // Add methods and virtuals
  1931. Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
  1932. if (name.match(/^(constructor)$/)) {
  1933. return;
  1934. }
  1935. const method = Object.getOwnPropertyDescriptor(model.prototype, name);
  1936. if (!virtualsOnly) {
  1937. if (typeof method.value === 'function') {
  1938. this.method(name, method.value);
  1939. }
  1940. }
  1941. if (typeof method.get === 'function') {
  1942. if (this.virtuals[name]) {
  1943. this.virtuals[name].getters = [];
  1944. }
  1945. this.virtual(name).get(method.get);
  1946. }
  1947. if (typeof method.set === 'function') {
  1948. if (this.virtuals[name]) {
  1949. this.virtuals[name].setters = [];
  1950. }
  1951. this.virtual(name).set(method.set);
  1952. }
  1953. }, this);
  1954. return this;
  1955. };
  1956. /*!
  1957. * ignore
  1958. */
  1959. Schema.prototype._getSchema = function(path) {
  1960. const _this = this;
  1961. const pathschema = _this.path(path);
  1962. const resultPath = [];
  1963. if (pathschema) {
  1964. pathschema.$fullPath = path;
  1965. return pathschema;
  1966. }
  1967. function search(parts, schema) {
  1968. let p = parts.length + 1;
  1969. let foundschema;
  1970. let trypath;
  1971. while (p--) {
  1972. trypath = parts.slice(0, p).join('.');
  1973. foundschema = schema.path(trypath);
  1974. if (foundschema) {
  1975. resultPath.push(trypath);
  1976. if (foundschema.caster) {
  1977. // array of Mixed?
  1978. if (foundschema.caster instanceof MongooseTypes.Mixed) {
  1979. foundschema.caster.$fullPath = resultPath.join('.');
  1980. return foundschema.caster;
  1981. }
  1982. // Now that we found the array, we need to check if there
  1983. // are remaining document paths to look up for casting.
  1984. // Also we need to handle array.$.path since schema.path
  1985. // doesn't work for that.
  1986. // If there is no foundschema.schema we are dealing with
  1987. // a path like array.$
  1988. if (p !== parts.length) {
  1989. if (foundschema.schema) {
  1990. let ret;
  1991. if (parts[p] === '$' || isArrayFilter(parts[p])) {
  1992. if (p + 1 === parts.length) {
  1993. // comments.$
  1994. return foundschema;
  1995. }
  1996. // comments.$.comments.$.title
  1997. ret = search(parts.slice(p + 1), foundschema.schema);
  1998. if (ret) {
  1999. ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
  2000. !foundschema.schema.$isSingleNested;
  2001. }
  2002. return ret;
  2003. }
  2004. // this is the last path of the selector
  2005. ret = search(parts.slice(p), foundschema.schema);
  2006. if (ret) {
  2007. ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
  2008. !foundschema.schema.$isSingleNested;
  2009. }
  2010. return ret;
  2011. }
  2012. }
  2013. } else if (foundschema.$isSchemaMap) {
  2014. if (p >= parts.length) {
  2015. return foundschema;
  2016. }
  2017. // Any path in the map will be an instance of the map's embedded schematype
  2018. if (p + 1 >= parts.length) {
  2019. return foundschema.$__schemaType;
  2020. }
  2021. const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema);
  2022. return ret;
  2023. }
  2024. foundschema.$fullPath = resultPath.join('.');
  2025. return foundschema;
  2026. }
  2027. }
  2028. }
  2029. // look for arrays
  2030. const parts = path.split('.');
  2031. for (let i = 0; i < parts.length; ++i) {
  2032. if (parts[i] === '$' || isArrayFilter(parts[i])) {
  2033. // Re: gh-5628, because `schema.path()` doesn't take $ into account.
  2034. parts[i] = '0';
  2035. }
  2036. }
  2037. return search(parts, _this);
  2038. };
  2039. /*!
  2040. * ignore
  2041. */
  2042. Schema.prototype._getPathType = function(path) {
  2043. const _this = this;
  2044. const pathschema = _this.path(path);
  2045. if (pathschema) {
  2046. return 'real';
  2047. }
  2048. function search(parts, schema) {
  2049. let p = parts.length + 1,
  2050. foundschema,
  2051. trypath;
  2052. while (p--) {
  2053. trypath = parts.slice(0, p).join('.');
  2054. foundschema = schema.path(trypath);
  2055. if (foundschema) {
  2056. if (foundschema.caster) {
  2057. // array of Mixed?
  2058. if (foundschema.caster instanceof MongooseTypes.Mixed) {
  2059. return { schema: foundschema, pathType: 'mixed' };
  2060. }
  2061. // Now that we found the array, we need to check if there
  2062. // are remaining document paths to look up for casting.
  2063. // Also we need to handle array.$.path since schema.path
  2064. // doesn't work for that.
  2065. // If there is no foundschema.schema we are dealing with
  2066. // a path like array.$
  2067. if (p !== parts.length && foundschema.schema) {
  2068. if (parts[p] === '$' || isArrayFilter(parts[p])) {
  2069. if (p === parts.length - 1) {
  2070. return { schema: foundschema, pathType: 'nested' };
  2071. }
  2072. // comments.$.comments.$.title
  2073. return search(parts.slice(p + 1), foundschema.schema);
  2074. }
  2075. // this is the last path of the selector
  2076. return search(parts.slice(p), foundschema.schema);
  2077. }
  2078. return {
  2079. schema: foundschema,
  2080. pathType: foundschema.$isSingleNested ? 'nested' : 'array'
  2081. };
  2082. }
  2083. return { schema: foundschema, pathType: 'real' };
  2084. } else if (p === parts.length && schema.nested[trypath]) {
  2085. return { schema: schema, pathType: 'nested' };
  2086. }
  2087. }
  2088. return { schema: foundschema || schema, pathType: 'undefined' };
  2089. }
  2090. // look for arrays
  2091. return search(path.split('.'), _this);
  2092. };
  2093. /*!
  2094. * ignore
  2095. */
  2096. function isArrayFilter(piece) {
  2097. return piece.startsWith('$[') && piece.endsWith(']');
  2098. }
  2099. /*!
  2100. * Called by `compile()` _right before_ compiling. Good for making any changes to
  2101. * the schema that should respect options set by plugins, like `id`
  2102. */
  2103. Schema.prototype._preCompile = function _preCompile() {
  2104. idGetter(this);
  2105. };
  2106. /*!
  2107. * Module exports.
  2108. */
  2109. module.exports = exports = Schema;
  2110. // require down here because of reference issues
  2111. /**
  2112. * The various built-in Mongoose Schema Types.
  2113. *
  2114. * #### Example:
  2115. *
  2116. * const mongoose = require('mongoose');
  2117. * const ObjectId = mongoose.Schema.Types.ObjectId;
  2118. *
  2119. * #### Types:
  2120. *
  2121. * - [String](/docs/schematypes.html#strings)
  2122. * - [Number](/docs/schematypes.html#numbers)
  2123. * - [Boolean](/docs/schematypes.html#booleans) | Bool
  2124. * - [Array](/docs/schematypes.html#arrays)
  2125. * - [Buffer](/docs/schematypes.html#buffers)
  2126. * - [Date](/docs/schematypes.html#dates)
  2127. * - [ObjectId](/docs/schematypes.html#objectids) | Oid
  2128. * - [Mixed](/docs/schematypes.html#mixed)
  2129. *
  2130. * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
  2131. *
  2132. * const Mixed = mongoose.Schema.Types.Mixed;
  2133. * new mongoose.Schema({ _user: Mixed })
  2134. *
  2135. * @api public
  2136. */
  2137. Schema.Types = MongooseTypes = require('./schema/index');
  2138. /*!
  2139. * ignore
  2140. */
  2141. exports.ObjectId = MongooseTypes.ObjectId;