Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

schema.js 50KB

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