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.7KB

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