schematype.js 36 KB

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