objectid.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 oid = require('../types/objectid');
  9. const utils = require('../utils');
  10. const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
  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. console.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. console.trace();
  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 => v instanceof oid;
  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 = v => {
  133. if (!(v instanceof oid)) {
  134. throw new Error(v + ' is not an instance of ObjectId');
  135. }
  136. return v;
  137. };
  138. }
  139. this._cast = caster;
  140. return this._cast;
  141. };
  142. /**
  143. * Override the function the required validator uses to check whether a string
  144. * passes the `required` check.
  145. *
  146. * ####Example:
  147. *
  148. * // Allow empty strings to pass `required` check
  149. * mongoose.Schema.Types.String.checkRequired(v => v != null);
  150. *
  151. * const M = mongoose.model({ str: { type: String, required: true } });
  152. * new M({ str: '' }).validateSync(); // `null`, validation passes!
  153. *
  154. * @param {Function} fn
  155. * @return {Function}
  156. * @function checkRequired
  157. * @static
  158. * @api public
  159. */
  160. ObjectId.checkRequired = SchemaType.checkRequired;
  161. /**
  162. * Check if the given value satisfies a required validator.
  163. *
  164. * @param {Any} value
  165. * @param {Document} doc
  166. * @return {Boolean}
  167. * @api public
  168. */
  169. ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
  170. if (SchemaType._isRef(this, value, doc, true)) {
  171. return !!value;
  172. }
  173. // `require('util').inherits()` does **not** copy static properties, and
  174. // plugins like mongoose-float use `inherits()` for pre-ES6.
  175. const _checkRequired = typeof this.constructor.checkRequired == 'function' ?
  176. this.constructor.checkRequired() :
  177. ObjectId.checkRequired();
  178. return _checkRequired(value);
  179. };
  180. /**
  181. * Casts to ObjectId
  182. *
  183. * @param {Object} value
  184. * @param {Object} doc
  185. * @param {Boolean} init whether this is an initialization cast
  186. * @api private
  187. */
  188. ObjectId.prototype.cast = function(value, doc, init) {
  189. if (SchemaType._isRef(this, value, doc, init)) {
  190. // wait! we may need to cast this to a document
  191. if (value === null || value === undefined) {
  192. return value;
  193. }
  194. // lazy load
  195. Document || (Document = require('./../document'));
  196. if (value instanceof Document) {
  197. value.$__.wasPopulated = true;
  198. return value;
  199. }
  200. // setting a populated path
  201. if (value instanceof oid) {
  202. return value;
  203. } else if ((value.constructor.name || '').toLowerCase() === 'objectid') {
  204. return new oid(value.toHexString());
  205. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
  206. throw new CastError('ObjectId', value, this.path, null, this);
  207. }
  208. // Handle the case where user directly sets a populated
  209. // path to a plain object; cast to the Model used in
  210. // the population query.
  211. const path = doc.$__fullPath(this.path);
  212. const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  213. const pop = owner.populated(path, true);
  214. let ret = value;
  215. if (!doc.$__.populated ||
  216. !doc.$__.populated[path] ||
  217. !doc.$__.populated[path].options ||
  218. !doc.$__.populated[path].options.options ||
  219. !doc.$__.populated[path].options.options.lean) {
  220. ret = new pop.options[populateModelSymbol](value);
  221. ret.$__.wasPopulated = true;
  222. }
  223. return ret;
  224. }
  225. const castObjectId = typeof this.constructor.cast === 'function' ?
  226. this.constructor.cast() :
  227. ObjectId.cast();
  228. try {
  229. return castObjectId(value);
  230. } catch (error) {
  231. throw new CastError('ObjectId', value, this.path, error, this);
  232. }
  233. };
  234. /*!
  235. * ignore
  236. */
  237. function handleSingle(val) {
  238. return this.cast(val);
  239. }
  240. ObjectId.prototype.$conditionalHandlers =
  241. utils.options(SchemaType.prototype.$conditionalHandlers, {
  242. $gt: handleSingle,
  243. $gte: handleSingle,
  244. $lt: handleSingle,
  245. $lte: handleSingle
  246. });
  247. /*!
  248. * ignore
  249. */
  250. function defaultId() {
  251. return new oid();
  252. }
  253. defaultId.$runBeforeSetters = true;
  254. function resetId(v) {
  255. Document || (Document = require('./../document'));
  256. if (this instanceof Document) {
  257. if (v === void 0) {
  258. const _v = new oid;
  259. this.$__._id = _v;
  260. return _v;
  261. }
  262. this.$__._id = v;
  263. }
  264. return v;
  265. }
  266. /*!
  267. * Module exports.
  268. */
  269. module.exports = ObjectId;