objectId.js 8.1 KB

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