objectid.js 6.6 KB

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