schema.js 62 KB

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