objectid.js 6.7 KB

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