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.

schematype.js 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const MongooseError = require('./error');
  6. const $exists = require('./schema/operators/exists');
  7. const $type = require('./schema/operators/type');
  8. const get = require('./helpers/get');
  9. const immediate = require('./helpers/immediate');
  10. const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
  11. const util = require('util');
  12. const utils = require('./utils');
  13. const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol;
  14. const CastError = MongooseError.CastError;
  15. const ValidatorError = MongooseError.ValidatorError;
  16. /**
  17. * SchemaType constructor. Do **not** instantiate `SchemaType` directly.
  18. * Mongoose converts your schema paths into SchemaTypes automatically.
  19. *
  20. * ####Example:
  21. *
  22. * const schema = new Schema({ name: String });
  23. * schema.path('name') instanceof SchemaType; // true
  24. *
  25. * @param {String} path
  26. * @param {Object} [options]
  27. * @param {String} [instance]
  28. * @api public
  29. */
  30. function SchemaType(path, options, instance) {
  31. this[schemaTypeSymbol] = true;
  32. this.path = path;
  33. this.instance = instance;
  34. this.validators = [];
  35. this.getters = this.constructor.hasOwnProperty('getters') ?
  36. this.constructor.getters.slice() :
  37. [];
  38. this.setters = [];
  39. this.options = options;
  40. this._index = null;
  41. this.selected;
  42. for (const prop in options) {
  43. if (this[prop] && typeof this[prop] === 'function') {
  44. // { unique: true, index: true }
  45. if (prop === 'index' && this._index) {
  46. if (options.index === false) {
  47. const index = this._index;
  48. if (typeof index === 'object' && index != null) {
  49. if (index.unique) {
  50. throw new Error('Path "' + this.path + '" may not have `index` ' +
  51. 'set to false and `unique` set to true');
  52. }
  53. if (index.sparse) {
  54. throw new Error('Path "' + this.path + '" may not have `index` ' +
  55. 'set to false and `sparse` set to true');
  56. }
  57. }
  58. this._index = false;
  59. }
  60. continue;
  61. }
  62. const val = options[prop];
  63. // Special case so we don't screw up array defaults, see gh-5780
  64. if (prop === 'default') {
  65. this.default(val);
  66. continue;
  67. }
  68. const opts = Array.isArray(val) ? val : [val];
  69. this[prop].apply(this, opts);
  70. }
  71. }
  72. Object.defineProperty(this, '$$context', {
  73. enumerable: false,
  74. configurable: false,
  75. writable: true,
  76. value: null
  77. });
  78. }
  79. /**
  80. * Get/set the function used to cast arbitrary values to this type.
  81. *
  82. * ####Example:
  83. *
  84. * // Disallow `null` for numbers, and don't try to cast any values to
  85. * // numbers, so even strings like '123' will cause a CastError.
  86. * mongoose.Number.cast(function(v) {
  87. * assert.ok(v === undefined || typeof v === 'number');
  88. * return v;
  89. * });
  90. *
  91. * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed
  92. * @return {Function}
  93. * @static
  94. * @receiver SchemaType
  95. * @function cast
  96. * @api public
  97. */
  98. SchemaType.cast = function cast(caster) {
  99. if (arguments.length === 0) {
  100. return this._cast;
  101. }
  102. if (caster === false) {
  103. caster = v => v;
  104. }
  105. this._cast = caster;
  106. return this._cast;
  107. };
  108. /**
  109. * Attaches a getter for all instances of this schema type.
  110. *
  111. * ####Example:
  112. *
  113. * // Make all numbers round down
  114. * mongoose.Number.get(function(v) { return Math.floor(v); });
  115. *
  116. * @param {Function} getter
  117. * @return {this}
  118. * @static
  119. * @receiver SchemaType
  120. * @function get
  121. * @api public
  122. */
  123. SchemaType.get = function(getter) {
  124. this.getters = this.hasOwnProperty('getters') ? this.getters : [];
  125. this.getters.push(getter);
  126. };
  127. /**
  128. * Sets a default value for this SchemaType.
  129. *
  130. * ####Example:
  131. *
  132. * var schema = new Schema({ n: { type: Number, default: 10 })
  133. * var M = db.model('M', schema)
  134. * var m = new M;
  135. * console.log(m.n) // 10
  136. *
  137. * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.
  138. *
  139. * ####Example:
  140. *
  141. * // values are cast:
  142. * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
  143. * var M = db.model('M', schema)
  144. * var m = new M;
  145. * console.log(m.aNumber) // 4.815162342
  146. *
  147. * // default unique objects for Mixed types:
  148. * var schema = new Schema({ mixed: Schema.Types.Mixed });
  149. * schema.path('mixed').default(function () {
  150. * return {};
  151. * });
  152. *
  153. * // if we don't use a function to return object literals for Mixed defaults,
  154. * // each document will receive a reference to the same object literal creating
  155. * // a "shared" object instance:
  156. * var schema = new Schema({ mixed: Schema.Types.Mixed });
  157. * schema.path('mixed').default({});
  158. * var M = db.model('M', schema);
  159. * var m1 = new M;
  160. * m1.mixed.added = 1;
  161. * console.log(m1.mixed); // { added: 1 }
  162. * var m2 = new M;
  163. * console.log(m2.mixed); // { added: 1 }
  164. *
  165. * @param {Function|any} val the default value
  166. * @return {defaultValue}
  167. * @api public
  168. */
  169. SchemaType.prototype.default = function(val) {
  170. if (arguments.length === 1) {
  171. if (val === void 0) {
  172. this.defaultValue = void 0;
  173. return void 0;
  174. }
  175. this.defaultValue = val;
  176. return this.defaultValue;
  177. } else if (arguments.length > 1) {
  178. this.defaultValue = utils.args(arguments);
  179. }
  180. return this.defaultValue;
  181. };
  182. /**
  183. * Declares the index options for this schematype.
  184. *
  185. * ####Example:
  186. *
  187. * var s = new Schema({ name: { type: String, index: true })
  188. * var s = new Schema({ loc: { type: [Number], index: 'hashed' })
  189. * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
  190. * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
  191. * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
  192. * Schema.path('my.path').index(true);
  193. * Schema.path('my.date').index({ expires: 60 });
  194. * Schema.path('my.path').index({ unique: true, sparse: true });
  195. *
  196. * ####NOTE:
  197. *
  198. * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background)
  199. * by default. If `background` is set to `false`, MongoDB will not execute any
  200. * read/write operations you send until the index build.
  201. * Specify `background: false` to override Mongoose's default._
  202. *
  203. * @param {Object|Boolean|String} options
  204. * @return {SchemaType} this
  205. * @api public
  206. */
  207. SchemaType.prototype.index = function(options) {
  208. this._index = options;
  209. utils.expires(this._index);
  210. return this;
  211. };
  212. /**
  213. * Declares an unique index.
  214. *
  215. * ####Example:
  216. *
  217. * var s = new Schema({ name: { type: String, unique: true }});
  218. * Schema.path('name').index({ unique: true });
  219. *
  220. * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
  221. *
  222. * @param {Boolean} bool
  223. * @return {SchemaType} this
  224. * @api public
  225. */
  226. SchemaType.prototype.unique = function(bool) {
  227. if (this._index === false) {
  228. if (!bool) {
  229. return;
  230. }
  231. throw new Error('Path "' + this.path + '" may not have `index` set to ' +
  232. 'false and `unique` set to true');
  233. }
  234. if (this._index == null || this._index === true) {
  235. this._index = {};
  236. } else if (typeof this._index === 'string') {
  237. this._index = {type: this._index};
  238. }
  239. this._index.unique = bool;
  240. return this;
  241. };
  242. /**
  243. * Declares a full text index.
  244. *
  245. * ###Example:
  246. *
  247. * var s = new Schema({name : {type: String, text : true })
  248. * Schema.path('name').index({text : true});
  249. * @param {Boolean} bool
  250. * @return {SchemaType} this
  251. * @api public
  252. */
  253. SchemaType.prototype.text = function(bool) {
  254. if (this._index === false) {
  255. if (!bool) {
  256. return;
  257. }
  258. throw new Error('Path "' + this.path + '" may not have `index` set to ' +
  259. 'false and `text` set to true');
  260. }
  261. if (this._index === null || this._index === undefined ||
  262. typeof this._index === 'boolean') {
  263. this._index = {};
  264. } else if (typeof this._index === 'string') {
  265. this._index = {type: this._index};
  266. }
  267. this._index.text = bool;
  268. return this;
  269. };
  270. /**
  271. * Declares a sparse index.
  272. *
  273. * ####Example:
  274. *
  275. * var s = new Schema({ name: { type: String, sparse: true })
  276. * Schema.path('name').index({ sparse: true });
  277. *
  278. * @param {Boolean} bool
  279. * @return {SchemaType} this
  280. * @api public
  281. */
  282. SchemaType.prototype.sparse = function(bool) {
  283. if (this._index === false) {
  284. if (!bool) {
  285. return;
  286. }
  287. throw new Error('Path "' + this.path + '" may not have `index` set to ' +
  288. 'false and `sparse` set to true');
  289. }
  290. if (this._index == null || typeof this._index === 'boolean') {
  291. this._index = {};
  292. } else if (typeof this._index === 'string') {
  293. this._index = {type: this._index};
  294. }
  295. this._index.sparse = bool;
  296. return this;
  297. };
  298. /**
  299. * Adds a setter to this schematype.
  300. *
  301. * ####Example:
  302. *
  303. * function capitalize (val) {
  304. * if (typeof val !== 'string') val = '';
  305. * return val.charAt(0).toUpperCase() + val.substring(1);
  306. * }
  307. *
  308. * // defining within the schema
  309. * var s = new Schema({ name: { type: String, set: capitalize }});
  310. *
  311. * // or with the SchemaType
  312. * var s = new Schema({ name: String })
  313. * s.path('name').set(capitalize);
  314. *
  315. * Setters allow you to transform the data before it gets to the raw mongodb
  316. * document or query.
  317. *
  318. * Suppose you are implementing user registration for a website. Users provide
  319. * an email and password, which gets saved to mongodb. The email is a string
  320. * that you will want to normalize to lower case, in order to avoid one email
  321. * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM.
  322. *
  323. * You can set up email lower case normalization easily via a Mongoose setter.
  324. *
  325. * function toLower(v) {
  326. * return v.toLowerCase();
  327. * }
  328. *
  329. * var UserSchema = new Schema({
  330. * email: { type: String, set: toLower }
  331. * });
  332. *
  333. * var User = db.model('User', UserSchema);
  334. *
  335. * var user = new User({email: 'AVENUE@Q.COM'});
  336. * console.log(user.email); // 'avenue@q.com'
  337. *
  338. * // or
  339. * var user = new User();
  340. * user.email = 'Avenue@Q.com';
  341. * console.log(user.email); // 'avenue@q.com'
  342. * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'
  343. *
  344. * As you can see above, setters allow you to transform the data before it
  345. * stored in MongoDB, or before executing a query.
  346. *
  347. * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._
  348. *
  349. * new Schema({ email: { type: String, lowercase: true }})
  350. *
  351. * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.
  352. *
  353. * function inspector (val, schematype) {
  354. * if (schematype.options.required) {
  355. * return schematype.path + ' is required';
  356. * } else {
  357. * return val;
  358. * }
  359. * }
  360. *
  361. * var VirusSchema = new Schema({
  362. * name: { type: String, required: true, set: inspector },
  363. * taxonomy: { type: String, set: inspector }
  364. * })
  365. *
  366. * var Virus = db.model('Virus', VirusSchema);
  367. * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
  368. *
  369. * console.log(v.name); // name is required
  370. * console.log(v.taxonomy); // Parvovirinae
  371. *
  372. * You can also use setters to modify other properties on the document. If
  373. * you're setting a property `name` on a document, the setter will run with
  374. * `this` as the document. Be careful, in mongoose 5 setters will also run
  375. * when querying by `name` with `this` as the query.
  376. *
  377. * ```javascript
  378. * const nameSchema = new Schema({ name: String, keywords: [String] });
  379. * nameSchema.path('name').set(function(v) {
  380. * // Need to check if `this` is a document, because in mongoose 5
  381. * // setters will also run on queries, in which case `this` will be a
  382. * // mongoose query object.
  383. * if (this instanceof Document && v != null) {
  384. * this.keywords = v.split(' ');
  385. * }
  386. * return v;
  387. * });
  388. * ```
  389. *
  390. * @param {Function} fn
  391. * @return {SchemaType} this
  392. * @api public
  393. */
  394. SchemaType.prototype.set = function(fn) {
  395. if (typeof fn !== 'function') {
  396. throw new TypeError('A setter must be a function.');
  397. }
  398. this.setters.push(fn);
  399. return this;
  400. };
  401. /**
  402. * Adds a getter to this schematype.
  403. *
  404. * ####Example:
  405. *
  406. * function dob (val) {
  407. * if (!val) return val;
  408. * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
  409. * }
  410. *
  411. * // defining within the schema
  412. * var s = new Schema({ born: { type: Date, get: dob })
  413. *
  414. * // or by retreiving its SchemaType
  415. * var s = new Schema({ born: Date })
  416. * s.path('born').get(dob)
  417. *
  418. * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.
  419. *
  420. * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:
  421. *
  422. * function obfuscate (cc) {
  423. * return '****-****-****-' + cc.slice(cc.length-4, cc.length);
  424. * }
  425. *
  426. * var AccountSchema = new Schema({
  427. * creditCardNumber: { type: String, get: obfuscate }
  428. * });
  429. *
  430. * var Account = db.model('Account', AccountSchema);
  431. *
  432. * Account.findById(id, function (err, found) {
  433. * console.log(found.creditCardNumber); // '****-****-****-1234'
  434. * });
  435. *
  436. * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.
  437. *
  438. * function inspector (val, schematype) {
  439. * if (schematype.options.required) {
  440. * return schematype.path + ' is required';
  441. * } else {
  442. * return schematype.path + ' is not';
  443. * }
  444. * }
  445. *
  446. * var VirusSchema = new Schema({
  447. * name: { type: String, required: true, get: inspector },
  448. * taxonomy: { type: String, get: inspector }
  449. * })
  450. *
  451. * var Virus = db.model('Virus', VirusSchema);
  452. *
  453. * Virus.findById(id, function (err, virus) {
  454. * console.log(virus.name); // name is required
  455. * console.log(virus.taxonomy); // taxonomy is not
  456. * })
  457. *
  458. * @param {Function} fn
  459. * @return {SchemaType} this
  460. * @api public
  461. */
  462. SchemaType.prototype.get = function(fn) {
  463. if (typeof fn !== 'function') {
  464. throw new TypeError('A getter must be a function.');
  465. }
  466. this.getters.push(fn);
  467. return this;
  468. };
  469. /**
  470. * Adds validator(s) for this document path.
  471. *
  472. * Validators always receive the value to validate as their first argument and
  473. * must return `Boolean`. Returning `false` or throwing an error means
  474. * validation failed.
  475. *
  476. * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used.
  477. *
  478. * ####Examples:
  479. *
  480. * // make sure every value is equal to "something"
  481. * function validator (val) {
  482. * return val == 'something';
  483. * }
  484. * new Schema({ name: { type: String, validate: validator }});
  485. *
  486. * // with a custom error message
  487. *
  488. * var custom = [validator, 'Uh oh, {PATH} does not equal "something".']
  489. * new Schema({ name: { type: String, validate: custom }});
  490. *
  491. * // adding many validators at a time
  492. *
  493. * var many = [
  494. * { validator: validator, msg: 'uh oh' }
  495. * , { validator: anotherValidator, msg: 'failed' }
  496. * ]
  497. * new Schema({ name: { type: String, validate: many }});
  498. *
  499. * // or utilizing SchemaType methods directly:
  500. *
  501. * var schema = new Schema({ name: 'string' });
  502. * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');
  503. *
  504. * ####Error message templates:
  505. *
  506. * From the examples above, you may have noticed that error messages support
  507. * basic templating. There are a few other template keywords besides `{PATH}`
  508. * and `{VALUE}` too. To find out more, details are available
  509. * [here](#error_messages_MongooseError.messages).
  510. *
  511. * If Mongoose's built-in error message templating isn't enough, Mongoose
  512. * supports setting the `message` property to a function.
  513. *
  514. * schema.path('name').validate({
  515. * validator: function() { return v.length > 5; },
  516. * // `errors['name']` will be "name must have length 5, got 'foo'"
  517. * message: function(props) {
  518. * return `${props.path} must have length 5, got '${props.value}'`;
  519. * }
  520. * });
  521. *
  522. * To bypass Mongoose's error messages and just copy the error message that
  523. * the validator throws, do this:
  524. *
  525. * schema.path('name').validate({
  526. * validator: function() { throw new Error('Oops!'); },
  527. * // `errors['name']` will be "Oops!"
  528. * message: function(props) { return props.reason.message; }
  529. * });
  530. *
  531. * ####Asynchronous validation:
  532. *
  533. * Mongoose supports validators that return a promise. A validator that returns
  534. * a promise is called an _async validator_. Async validators run in
  535. * parallel, and `validate()` will wait until all async validators have settled.
  536. *
  537. * schema.path('name').validate({
  538. * validator: function (value) {
  539. * return new Promise(function (resolve, reject) {
  540. * resolve(false); // validation failed
  541. * });
  542. * }
  543. * });
  544. *
  545. * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.
  546. *
  547. * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate).
  548. *
  549. * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along.
  550. *
  551. * var conn = mongoose.createConnection(..);
  552. * conn.on('error', handleError);
  553. *
  554. * var Product = conn.model('Product', yourSchema);
  555. * var dvd = new Product(..);
  556. * dvd.save(); // emits error on the `conn` above
  557. *
  558. * If you want to handle these errors at the Model level, add an `error`
  559. * listener to your Model as shown below.
  560. *
  561. * // registering an error listener on the Model lets us handle errors more locally
  562. * Product.on('error', handleError);
  563. *
  564. * @param {RegExp|Function|Object} obj validator function, or hash describing options
  565. * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns falsy (except `undefined`) or throws an error, validation fails.
  566. * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string
  567. * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators.
  568. * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string
  569. * @param {String} [type] optional validator type
  570. * @return {SchemaType} this
  571. * @api public
  572. */
  573. SchemaType.prototype.validate = function(obj, message, type) {
  574. if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') {
  575. let properties;
  576. if (message instanceof Object && !type) {
  577. properties = utils.clone(message);
  578. if (!properties.message) {
  579. properties.message = properties.msg;
  580. }
  581. properties.validator = obj;
  582. properties.type = properties.type || 'user defined';
  583. } else {
  584. if (!message) {
  585. message = MongooseError.messages.general.default;
  586. }
  587. if (!type) {
  588. type = 'user defined';
  589. }
  590. properties = {message: message, type: type, validator: obj};
  591. }
  592. if (properties.isAsync) {
  593. handleIsAsync();
  594. }
  595. this.validators.push(properties);
  596. return this;
  597. }
  598. let i;
  599. let length;
  600. let arg;
  601. for (i = 0, length = arguments.length; i < length; i++) {
  602. arg = arguments[i];
  603. if (!utils.isPOJO(arg)) {
  604. const msg = 'Invalid validator. Received (' + typeof arg + ') '
  605. + arg
  606. + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate';
  607. throw new Error(msg);
  608. }
  609. this.validate(arg.validator, arg);
  610. }
  611. return this;
  612. };
  613. /*!
  614. * ignore
  615. */
  616. const handleIsAsync = util.deprecate(function handleIsAsync() {},
  617. 'Mongoose: the `isAsync` option for custom validators is deprecated. Make ' +
  618. 'your async validators return a promise instead: ' +
  619. 'https://mongoosejs.com/docs/validation.html#async-custom-validators');
  620. /**
  621. * Adds a required validator to this SchemaType. The validator gets added
  622. * to the front of this SchemaType's validators array using `unshift()`.
  623. *
  624. * ####Example:
  625. *
  626. * var s = new Schema({ born: { type: Date, required: true })
  627. *
  628. * // or with custom error message
  629. *
  630. * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
  631. *
  632. * // or with a function
  633. *
  634. * var s = new Schema({
  635. * userId: ObjectId,
  636. * username: {
  637. * type: String,
  638. * required: function() { return this.userId != null; }
  639. * }
  640. * })
  641. *
  642. * // or with a function and a custom message
  643. * var s = new Schema({
  644. * userId: ObjectId,
  645. * username: {
  646. * type: String,
  647. * required: [
  648. * function() { return this.userId != null; },
  649. * 'username is required if id is specified'
  650. * ]
  651. * }
  652. * })
  653. *
  654. * // or through the path API
  655. *
  656. * Schema.path('name').required(true);
  657. *
  658. * // with custom error messaging
  659. *
  660. * Schema.path('name').required(true, 'grrr :( ');
  661. *
  662. * // or make a path conditionally required based on a function
  663. * var isOver18 = function() { return this.age >= 18; };
  664. * Schema.path('voterRegistrationId').required(isOver18);
  665. *
  666. * The required validator uses the SchemaType's `checkRequired` function to
  667. * determine whether a given value satisfies the required validator. By default,
  668. * a value satisfies the required validator if `val != null` (that is, if
  669. * the value is not null nor undefined). However, most built-in mongoose schema
  670. * types override the default `checkRequired` function:
  671. *
  672. * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object
  673. * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean
  674. * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.
  675. * @param {String} [message] optional custom error message
  676. * @return {SchemaType} this
  677. * @see Customized Error Messages #error_messages_MongooseError-messages
  678. * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired
  679. * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired
  680. * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName
  681. * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min
  682. * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto
  683. * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired
  684. * @api public
  685. */
  686. SchemaType.prototype.required = function(required, message) {
  687. let customOptions = {};
  688. if (typeof required === 'object') {
  689. customOptions = required;
  690. message = customOptions.message || message;
  691. required = required.isRequired;
  692. }
  693. if (required === false) {
  694. this.validators = this.validators.filter(function(v) {
  695. return v.validator !== this.requiredValidator;
  696. }, this);
  697. this.isRequired = false;
  698. delete this.originalRequiredValue;
  699. return this;
  700. }
  701. const _this = this;
  702. this.isRequired = true;
  703. this.requiredValidator = function(v) {
  704. const cachedRequired = get(this, '$__.cachedRequired');
  705. // no validation when this path wasn't selected in the query.
  706. if (cachedRequired != null && !this.isSelected(_this.path) && !this.isModified(_this.path)) {
  707. return true;
  708. }
  709. // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we
  710. // don't call required functions multiple times in one validate call
  711. // See gh-6801
  712. if (cachedRequired != null && _this.path in cachedRequired) {
  713. const res = cachedRequired[_this.path] ?
  714. _this.checkRequired(v, this) :
  715. true;
  716. delete cachedRequired[_this.path];
  717. return res;
  718. } else if (typeof required === 'function') {
  719. return required.apply(this) ? _this.checkRequired(v, this) : true;
  720. }
  721. return _this.checkRequired(v, this);
  722. };
  723. this.originalRequiredValue = required;
  724. if (typeof required === 'string') {
  725. message = required;
  726. required = undefined;
  727. }
  728. const msg = message || MongooseError.messages.general.required;
  729. this.validators.unshift(Object.assign({}, customOptions, {
  730. validator: this.requiredValidator,
  731. message: msg,
  732. type: 'required'
  733. }));
  734. return this;
  735. };
  736. /**
  737. * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
  738. * looks at to determine the foreign collection it should query.
  739. *
  740. * ####Example:
  741. * const userSchema = new Schema({ name: String });
  742. * const User = mongoose.model('User', userSchema);
  743. *
  744. * const postSchema = new Schema({ user: mongoose.ObjectId });
  745. * postSchema.path('user').ref('User'); // By model name
  746. * postSchema.path('user').ref(User); // Can pass the model as well
  747. *
  748. * // Or you can just declare the `ref` inline in your schema
  749. * const postSchema2 = new Schema({
  750. * user: { type: mongoose.ObjectId, ref: User }
  751. * });
  752. *
  753. * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model.
  754. * @return {SchemaType} this
  755. * @api public
  756. */
  757. SchemaType.prototype.ref = function(ref) {
  758. this.options.ref = ref;
  759. return this;
  760. };
  761. /**
  762. * Gets the default value
  763. *
  764. * @param {Object} scope the scope which callback are executed
  765. * @param {Boolean} init
  766. * @api private
  767. */
  768. SchemaType.prototype.getDefault = function(scope, init) {
  769. let ret = typeof this.defaultValue === 'function'
  770. ? this.defaultValue.call(scope)
  771. : this.defaultValue;
  772. if (ret !== null && ret !== undefined) {
  773. if (typeof ret === 'object' && (!this.options || !this.options.shared)) {
  774. ret = utils.clone(ret);
  775. }
  776. const casted = this.cast(ret, scope, init);
  777. if (casted && casted.$isSingleNested) {
  778. casted.$parent = scope;
  779. }
  780. return casted;
  781. }
  782. return ret;
  783. };
  784. /*!
  785. * Applies setters without casting
  786. *
  787. * @api private
  788. */
  789. SchemaType.prototype._applySetters = function(value, scope, init, priorVal) {
  790. let v = value;
  791. const setters = this.setters;
  792. let len = setters.length;
  793. const caster = this.caster;
  794. while (len--) {
  795. v = setters[len].call(scope, v, this);
  796. }
  797. if (Array.isArray(v) && caster && caster.setters) {
  798. const newVal = [];
  799. for (let i = 0; i < v.length; i++) {
  800. newVal.push(caster.applySetters(v[i], scope, init, priorVal));
  801. }
  802. v = newVal;
  803. }
  804. return v;
  805. };
  806. /**
  807. * Applies setters
  808. *
  809. * @param {Object} value
  810. * @param {Object} scope
  811. * @param {Boolean} init
  812. * @api private
  813. */
  814. SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) {
  815. let v = this._applySetters(value, scope, init, priorVal, options);
  816. if (v == null) {
  817. return v;
  818. }
  819. // do not cast until all setters are applied #665
  820. v = this.cast(v, scope, init, priorVal, options);
  821. return v;
  822. };
  823. /**
  824. * Applies getters to a value
  825. *
  826. * @param {Object} value
  827. * @param {Object} scope
  828. * @api private
  829. */
  830. SchemaType.prototype.applyGetters = function(value, scope) {
  831. let v = value;
  832. const getters = this.getters;
  833. const len = getters.length;
  834. if (len === 0) {
  835. return v;
  836. }
  837. for (let i = 0; i < len; ++i) {
  838. v = getters[i].call(scope, v, this);
  839. }
  840. return v;
  841. };
  842. /**
  843. * Sets default `select()` behavior for this path.
  844. *
  845. * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level.
  846. *
  847. * ####Example:
  848. *
  849. * T = db.model('T', new Schema({ x: { type: String, select: true }}));
  850. * T.find(..); // field x will always be selected ..
  851. * // .. unless overridden;
  852. * T.find().select('-x').exec(callback);
  853. *
  854. * @param {Boolean} val
  855. * @return {SchemaType} this
  856. * @api public
  857. */
  858. SchemaType.prototype.select = function select(val) {
  859. this.selected = !!val;
  860. return this;
  861. };
  862. /**
  863. * Performs a validation of `value` using the validators declared for this SchemaType.
  864. *
  865. * @param {any} value
  866. * @param {Function} callback
  867. * @param {Object} scope
  868. * @api private
  869. */
  870. SchemaType.prototype.doValidate = function(value, fn, scope, options) {
  871. let err = false;
  872. const path = this.path;
  873. // Avoid non-object `validators`
  874. const validators = this.validators.
  875. filter(v => v != null && typeof v === 'object');
  876. let count = validators.length;
  877. if (!count) {
  878. return fn(null);
  879. }
  880. const validate = function(ok, validatorProperties) {
  881. if (err) {
  882. return;
  883. }
  884. if (ok === undefined || ok) {
  885. if (--count <= 0) {
  886. immediate(function() {
  887. fn(null);
  888. });
  889. }
  890. } else {
  891. const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
  892. err = new ErrorConstructor(validatorProperties);
  893. err[validatorErrorSymbol] = true;
  894. immediate(function() {
  895. fn(err);
  896. });
  897. }
  898. };
  899. const _this = this;
  900. validators.forEach(function(v) {
  901. if (err) {
  902. return;
  903. }
  904. const validator = v.validator;
  905. let ok;
  906. const validatorProperties = utils.clone(v);
  907. validatorProperties.path = options && options.path ? options.path : path;
  908. validatorProperties.value = value;
  909. if (validator instanceof RegExp) {
  910. validate(validator.test(value), validatorProperties);
  911. } else if (typeof validator === 'function') {
  912. if (value === undefined && validator !== _this.requiredValidator) {
  913. validate(true, validatorProperties);
  914. return;
  915. }
  916. if (validatorProperties.isAsync) {
  917. asyncValidate(validator, scope, value, validatorProperties, validate);
  918. } else {
  919. try {
  920. if (validatorProperties.propsParameter) {
  921. ok = validator.call(scope, value, validatorProperties);
  922. } else {
  923. ok = validator.call(scope, value);
  924. }
  925. } catch (error) {
  926. ok = false;
  927. validatorProperties.reason = error;
  928. if (error.message) {
  929. validatorProperties.message = error.message;
  930. }
  931. }
  932. if (ok != null && typeof ok.then === 'function') {
  933. ok.then(
  934. function(ok) { validate(ok, validatorProperties); },
  935. function(error) {
  936. validatorProperties.reason = error;
  937. ok = false;
  938. validate(ok, validatorProperties);
  939. });
  940. } else {
  941. validate(ok, validatorProperties);
  942. }
  943. }
  944. }
  945. });
  946. };
  947. /*!
  948. * Handle async validators
  949. */
  950. function asyncValidate(validator, scope, value, props, cb) {
  951. let called = false;
  952. const returnVal = validator.call(scope, value, function(ok, customMsg) {
  953. if (called) {
  954. return;
  955. }
  956. called = true;
  957. if (customMsg) {
  958. props.message = customMsg;
  959. }
  960. cb(ok, props);
  961. });
  962. if (typeof returnVal === 'boolean') {
  963. called = true;
  964. cb(returnVal, props);
  965. } else if (returnVal && typeof returnVal.then === 'function') {
  966. // Promise
  967. returnVal.then(
  968. function(ok) {
  969. if (called) {
  970. return;
  971. }
  972. called = true;
  973. cb(ok, props);
  974. },
  975. function(error) {
  976. if (called) {
  977. return;
  978. }
  979. called = true;
  980. props.reason = error;
  981. cb(false, props);
  982. });
  983. }
  984. }
  985. /**
  986. * Performs a validation of `value` using the validators declared for this SchemaType.
  987. *
  988. * ####Note:
  989. *
  990. * This method ignores the asynchronous validators.
  991. *
  992. * @param {any} value
  993. * @param {Object} scope
  994. * @return {MongooseError|undefined}
  995. * @api private
  996. */
  997. SchemaType.prototype.doValidateSync = function(value, scope, options) {
  998. let err = null;
  999. const path = this.path;
  1000. const count = this.validators.length;
  1001. if (!count) {
  1002. return null;
  1003. }
  1004. const validate = function(ok, validatorProperties) {
  1005. if (err) {
  1006. return;
  1007. }
  1008. if (ok !== undefined && !ok) {
  1009. const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
  1010. err = new ErrorConstructor(validatorProperties);
  1011. err[validatorErrorSymbol] = true;
  1012. }
  1013. };
  1014. let validators = this.validators;
  1015. if (value === void 0) {
  1016. if (this.validators.length > 0 && this.validators[0].type === 'required') {
  1017. validators = [this.validators[0]];
  1018. } else {
  1019. return null;
  1020. }
  1021. }
  1022. validators.forEach(function(v) {
  1023. if (err) {
  1024. return;
  1025. }
  1026. if (v == null || typeof v !== 'object') {
  1027. return;
  1028. }
  1029. const validator = v.validator;
  1030. const validatorProperties = utils.clone(v);
  1031. validatorProperties.path = options && options.path ? options.path : path;
  1032. validatorProperties.value = value;
  1033. let ok;
  1034. // Skip any explicit async validators. Validators that return a promise
  1035. // will still run, but won't trigger any errors.
  1036. if (validator.isAsync) {
  1037. return;
  1038. }
  1039. if (validator instanceof RegExp) {
  1040. validate(validator.test(value), validatorProperties);
  1041. } else if (typeof validator === 'function') {
  1042. try {
  1043. if (validatorProperties.propsParameter) {
  1044. ok = validator.call(scope, value, validatorProperties);
  1045. } else {
  1046. ok = validator.call(scope, value);
  1047. }
  1048. } catch (error) {
  1049. ok = false;
  1050. validatorProperties.reason = error;
  1051. }
  1052. // Skip any validators that return a promise, we can't handle those
  1053. // synchronously
  1054. if (ok != null && typeof ok.then === 'function') {
  1055. return;
  1056. }
  1057. validate(ok, validatorProperties);
  1058. }
  1059. });
  1060. return err;
  1061. };
  1062. /**
  1063. * Determines if value is a valid Reference.
  1064. *
  1065. * @param {SchemaType} self
  1066. * @param {Object} value
  1067. * @param {Document} doc
  1068. * @param {Boolean} init
  1069. * @return {Boolean}
  1070. * @api private
  1071. */
  1072. SchemaType._isRef = function(self, value, doc, init) {
  1073. // fast path
  1074. let ref = init && self.options && (self.options.ref || self.options.refPath);
  1075. if (!ref && doc && doc.$__ != null) {
  1076. // checks for
  1077. // - this populated with adhoc model and no ref was set in schema OR
  1078. // - setting / pushing values after population
  1079. const path = doc.$__fullPath(self.path);
  1080. const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  1081. ref = owner.populated(path);
  1082. }
  1083. if (ref) {
  1084. if (value == null) {
  1085. return true;
  1086. }
  1087. if (!Buffer.isBuffer(value) && // buffers are objects too
  1088. value._bsontype !== 'Binary' // raw binary value from the db
  1089. && utils.isObject(value) // might have deselected _id in population query
  1090. ) {
  1091. return true;
  1092. }
  1093. }
  1094. return false;
  1095. };
  1096. /*!
  1097. * ignore
  1098. */
  1099. function handleSingle(val) {
  1100. return this.castForQuery(val);
  1101. }
  1102. /*!
  1103. * ignore
  1104. */
  1105. function handleArray(val) {
  1106. const _this = this;
  1107. if (!Array.isArray(val)) {
  1108. return [this.castForQuery(val)];
  1109. }
  1110. return val.map(function(m) {
  1111. return _this.castForQuery(m);
  1112. });
  1113. }
  1114. /*!
  1115. * Just like handleArray, except also allows `[]` because surprisingly
  1116. * `$in: [1, []]` works fine
  1117. */
  1118. function handle$in(val) {
  1119. const _this = this;
  1120. if (!Array.isArray(val)) {
  1121. return [this.castForQuery(val)];
  1122. }
  1123. return val.map(function(m) {
  1124. if (Array.isArray(m) && m.length === 0) {
  1125. return m;
  1126. }
  1127. return _this.castForQuery(m);
  1128. });
  1129. }
  1130. /*!
  1131. * ignore
  1132. */
  1133. SchemaType.prototype.$conditionalHandlers = {
  1134. $all: handleArray,
  1135. $eq: handleSingle,
  1136. $in: handle$in,
  1137. $ne: handleSingle,
  1138. $nin: handleArray,
  1139. $exists: $exists,
  1140. $type: $type
  1141. };
  1142. /*!
  1143. * Wraps `castForQuery` to handle context
  1144. */
  1145. SchemaType.prototype.castForQueryWrapper = function(params) {
  1146. this.$$context = params.context;
  1147. if ('$conditional' in params) {
  1148. return this.castForQuery(params.$conditional, params.val);
  1149. }
  1150. if (params.$skipQueryCastForUpdate) {
  1151. return this._castForQuery(params.val);
  1152. }
  1153. return this.castForQuery(params.val);
  1154. };
  1155. /**
  1156. * Cast the given value with the given optional query operator.
  1157. *
  1158. * @param {String} [$conditional] query operator, like `$eq` or `$in`
  1159. * @param {any} val
  1160. * @api private
  1161. */
  1162. SchemaType.prototype.castForQuery = function($conditional, val) {
  1163. let handler;
  1164. if (arguments.length === 2) {
  1165. handler = this.$conditionalHandlers[$conditional];
  1166. if (!handler) {
  1167. throw new Error('Can\'t use ' + $conditional);
  1168. }
  1169. return handler.call(this, val);
  1170. }
  1171. val = $conditional;
  1172. return this._castForQuery(val);
  1173. };
  1174. /*!
  1175. * Internal switch for runSetters
  1176. *
  1177. * @api private
  1178. */
  1179. SchemaType.prototype._castForQuery = function(val) {
  1180. return this.applySetters(val, this.$$context);
  1181. };
  1182. /**
  1183. * Override the function the required validator uses to check whether a value
  1184. * passes the `required` check. Override this on the individual SchemaType.
  1185. *
  1186. * ####Example:
  1187. *
  1188. * // Use this to allow empty strings to pass the `required` validator
  1189. * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
  1190. *
  1191. * @param {Function} fn
  1192. * @return {Function}
  1193. * @static
  1194. * @receiver SchemaType
  1195. * @function checkRequired
  1196. * @api public
  1197. */
  1198. SchemaType.checkRequired = function(fn) {
  1199. if (arguments.length > 0) {
  1200. this._checkRequired = fn;
  1201. }
  1202. return this._checkRequired;
  1203. };
  1204. /**
  1205. * Default check for if this path satisfies the `required` validator.
  1206. *
  1207. * @param {any} val
  1208. * @api private
  1209. */
  1210. SchemaType.prototype.checkRequired = function(val) {
  1211. return val != null;
  1212. };
  1213. /*!
  1214. * ignore
  1215. */
  1216. SchemaType.prototype.clone = function() {
  1217. const options = Object.assign({}, this.options);
  1218. const schematype = new this.constructor(this.path, options, this.instance);
  1219. schematype.validators = this.validators.slice();
  1220. return schematype;
  1221. };
  1222. /*!
  1223. * Module exports.
  1224. */
  1225. module.exports = exports = SchemaType;
  1226. exports.CastError = CastError;
  1227. exports.ValidatorError = ValidatorError;