objectid.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions');
  6. const SchemaType = require('../schematype');
  7. const castObjectId = require('../cast/objectid');
  8. const getConstructorName = require('../helpers/getConstructorName');
  9. const oid = require('../types/objectid');
  10. const utils = require('../utils');
  11. const CastError = SchemaType.CastError;
  12. let Document;
  13. /**
  14. * ObjectId SchemaType constructor.
  15. *
  16. * @param {String} key
  17. * @param {Object} options
  18. * @inherits SchemaType
  19. * @api public
  20. */
  21. function ObjectId(key, options) {
  22. const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key);
  23. const suppressWarning = options && options.suppressWarning;
  24. if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) {
  25. utils.warn('mongoose: To create a new ObjectId please try ' +
  26. '`Mongoose.Types.ObjectId` instead of using ' +
  27. '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' +
  28. 'you\'re trying to create a hex char path in your schema.');
  29. }
  30. SchemaType.call(this, key, options, 'ObjectID');
  31. }
  32. /**
  33. * This schema type's name, to defend against minifiers that mangle
  34. * function names.
  35. *
  36. * @api public
  37. */
  38. ObjectId.schemaName = 'ObjectId';
  39. ObjectId.defaultOptions = {};
  40. /*!
  41. * Inherits from SchemaType.
  42. */
  43. ObjectId.prototype = Object.create(SchemaType.prototype);
  44. ObjectId.prototype.constructor = ObjectId;
  45. ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions;
  46. /**
  47. * Attaches a getter for all ObjectId instances
  48. *
  49. * ####Example:
  50. *
  51. * // Always convert to string when getting an ObjectId
  52. * mongoose.ObjectId.get(v => v.toString());
  53. *
  54. * const Model = mongoose.model('Test', new Schema({}));
  55. * typeof (new Model({})._id); // 'string'
  56. *
  57. * @param {Function} getter
  58. * @return {this}
  59. * @function get
  60. * @static
  61. * @api public
  62. */
  63. ObjectId.get = SchemaType.get;
  64. /**
  65. * Sets a default option for all ObjectId instances.
  66. *
  67. * ####Example:
  68. *
  69. * // Make all object ids have option `required` equal to true.
  70. * mongoose.Schema.ObjectId.set('required', true);
  71. *
  72. * const Order = mongoose.model('Order', new Schema({ userId: ObjectId }));
  73. * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required.
  74. *
  75. * @param {String} option - The option you'd like to set the value for
  76. * @param {*} value - value for option
  77. * @return {undefined}
  78. * @function set
  79. * @static
  80. * @api public
  81. */
  82. ObjectId.set = SchemaType.set;
  83. /**
  84. * Adds an auto-generated ObjectId default if turnOn is true.
  85. * @param {Boolean} turnOn auto generated ObjectId defaults
  86. * @api public
  87. * @return {SchemaType} this
  88. */
  89. ObjectId.prototype.auto = function(turnOn) {
  90. if (turnOn) {
  91. this.default(defaultId);
  92. this.set(resetId);
  93. }
  94. return this;
  95. };
  96. /*!
  97. * ignore
  98. */
  99. ObjectId._checkRequired = v => v instanceof oid;
  100. /*!
  101. * ignore
  102. */
  103. ObjectId._cast = castObjectId;
  104. /**
  105. * Get/set the function used to cast arbitrary values to objectids.
  106. *
  107. * ####Example:
  108. *
  109. * // Make Mongoose only try to cast length 24 strings. By default, any 12
  110. * // char string is a valid ObjectId.
  111. * const original = mongoose.ObjectId.cast();
  112. * mongoose.ObjectId.cast(v => {
  113. * assert.ok(typeof v !== 'string' || v.length === 24);
  114. * return original(v);
  115. * });
  116. *
  117. * // Or disable casting entirely
  118. * mongoose.ObjectId.cast(false);
  119. *
  120. * @param {Function} caster
  121. * @return {Function}
  122. * @function get
  123. * @static
  124. * @api public
  125. */
  126. ObjectId.cast = function cast(caster) {
  127. if (arguments.length === 0) {
  128. return this._cast;
  129. }
  130. if (caster === false) {
  131. caster = this._defaultCaster;
  132. }
  133. this._cast = caster;
  134. return this._cast;
  135. };
  136. /*!
  137. * ignore
  138. */
  139. ObjectId._defaultCaster = v => {
  140. if (!(v instanceof oid)) {
  141. throw new Error(v + ' is not an instance of ObjectId');
  142. }
  143. return v;
  144. };
  145. /**
  146. * Override the function the required validator uses to check whether a string
  147. * passes the `required` check.
  148. *
  149. * ####Example:
  150. *
  151. * // Allow empty strings to pass `required` check
  152. * mongoose.Schema.Types.String.checkRequired(v => v != null);
  153. *
  154. * const M = mongoose.model({ str: { type: String, required: true } });
  155. * new M({ str: '' }).validateSync(); // `null`, validation passes!
  156. *
  157. * @param {Function} fn
  158. * @return {Function}
  159. * @function checkRequired
  160. * @static
  161. * @api public
  162. */
  163. ObjectId.checkRequired = SchemaType.checkRequired;
  164. /**
  165. * Check if the given value satisfies a required validator.
  166. *
  167. * @param {Any} value
  168. * @param {Document} doc
  169. * @return {Boolean}
  170. * @api public
  171. */
  172. ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
  173. if (SchemaType._isRef(this, value, doc, true)) {
  174. return !!value;
  175. }
  176. // `require('util').inherits()` does **not** copy static properties, and
  177. // plugins like mongoose-float use `inherits()` for pre-ES6.
  178. const _checkRequired = typeof this.constructor.checkRequired == 'function' ?
  179. this.constructor.checkRequired() :
  180. ObjectId.checkRequired();
  181. return _checkRequired(value);
  182. };
  183. /**
  184. * Casts to ObjectId
  185. *
  186. * @param {Object} value
  187. * @param {Object} doc
  188. * @param {Boolean} init whether this is an initialization cast
  189. * @api private
  190. */
  191. ObjectId.prototype.cast = function(value, doc, init) {
  192. if (SchemaType._isRef(this, value, doc, init)) {
  193. // wait! we may need to cast this to a document
  194. if (value instanceof oid) {
  195. return value;
  196. } else if ((getConstructorName(value) || '').toLowerCase() === 'objectid') {
  197. return new oid(value.toHexString());
  198. }
  199. if (value == null || utils.isNonBuiltinObject(value)) {
  200. return this._castRef(value, doc, init);
  201. }
  202. }
  203. let castObjectId;
  204. if (typeof this._castFunction === 'function') {
  205. castObjectId = this._castFunction;
  206. } else if (typeof this.constructor.cast === 'function') {
  207. castObjectId = this.constructor.cast();
  208. } else {
  209. castObjectId = ObjectId.cast();
  210. }
  211. try {
  212. return castObjectId(value);
  213. } catch (error) {
  214. throw new CastError('ObjectId', value, this.path, error, this);
  215. }
  216. };
  217. /*!
  218. * ignore
  219. */
  220. function handleSingle(val) {
  221. return this.cast(val);
  222. }
  223. ObjectId.prototype.$conditionalHandlers =
  224. utils.options(SchemaType.prototype.$conditionalHandlers, {
  225. $gt: handleSingle,
  226. $gte: handleSingle,
  227. $lt: handleSingle,
  228. $lte: handleSingle
  229. });
  230. /*!
  231. * ignore
  232. */
  233. function defaultId() {
  234. return new oid();
  235. }
  236. defaultId.$runBeforeSetters = true;
  237. function resetId(v) {
  238. Document || (Document = require('./../document'));
  239. if (this instanceof Document) {
  240. if (v === void 0) {
  241. const _v = new oid();
  242. this.$__._id = _v;
  243. return _v;
  244. }
  245. this.$__._id = v;
  246. }
  247. return v;
  248. }
  249. /*!
  250. * Module exports.
  251. */
  252. module.exports = ObjectId;