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 54KB

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