Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

objectid.js 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. return this.constructor._checkRequired(value);
  151. };
  152. /**
  153. * Casts to ObjectId
  154. *
  155. * @param {Object} value
  156. * @param {Object} doc
  157. * @param {Boolean} init whether this is an initialization cast
  158. * @api private
  159. */
  160. ObjectId.prototype.cast = function(value, doc, init) {
  161. if (SchemaType._isRef(this, value, doc, init)) {
  162. // wait! we may need to cast this to a document
  163. if (value === null || value === undefined) {
  164. return value;
  165. }
  166. // lazy load
  167. Document || (Document = require('./../document'));
  168. if (value instanceof Document) {
  169. value.$__.wasPopulated = true;
  170. return value;
  171. }
  172. // setting a populated path
  173. if (value instanceof oid) {
  174. return value;
  175. } else if ((value.constructor.name || '').toLowerCase() === 'objectid') {
  176. return new oid(value.toHexString());
  177. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
  178. throw new CastError('ObjectId', value, this.path);
  179. }
  180. // Handle the case where user directly sets a populated
  181. // path to a plain object; cast to the Model used in
  182. // the population query.
  183. const path = doc.$__fullPath(this.path);
  184. const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  185. const pop = owner.populated(path, true);
  186. let ret = value;
  187. if (!doc.$__.populated ||
  188. !doc.$__.populated[path] ||
  189. !doc.$__.populated[path].options ||
  190. !doc.$__.populated[path].options.options ||
  191. !doc.$__.populated[path].options.options.lean) {
  192. ret = new pop.options.model(value);
  193. ret.$__.wasPopulated = true;
  194. }
  195. return ret;
  196. }
  197. try {
  198. return this.constructor.cast()(value);
  199. } catch (error) {
  200. throw new CastError('ObjectId', value, this.path);
  201. }
  202. };
  203. /*!
  204. * ignore
  205. */
  206. function handleSingle(val) {
  207. return this.cast(val);
  208. }
  209. ObjectId.prototype.$conditionalHandlers =
  210. utils.options(SchemaType.prototype.$conditionalHandlers, {
  211. $gt: handleSingle,
  212. $gte: handleSingle,
  213. $lt: handleSingle,
  214. $lte: handleSingle
  215. });
  216. /*!
  217. * ignore
  218. */
  219. function defaultId() {
  220. return new oid();
  221. }
  222. defaultId.$runBeforeSetters = true;
  223. function resetId(v) {
  224. Document || (Document = require('./../document'));
  225. if (this instanceof Document) {
  226. if (v === void 0) {
  227. const _v = new oid;
  228. this.$__._id = _v;
  229. return _v;
  230. }
  231. this.$__._id = v;
  232. }
  233. return v;
  234. }
  235. /*!
  236. * Module exports.
  237. */
  238. module.exports = ObjectId;