/node_modules/mongoose/lib/schema/documentarray.js

https://bitbucket.org/coleman333/smartsite · JavaScript · 397 lines · 241 code · 65 blank · 91 comment · 71 complexity · 6da4652a21add5b95187a9cd9b942ea4 MD5 · raw file

  1. /* eslint no-empty: 1 */
  2. /*!
  3. * Module dependencies.
  4. */
  5. var ArrayType = require('./array');
  6. var CastError = require('../error/cast');
  7. var EventEmitter = require('events').EventEmitter;
  8. var SchemaType = require('../schematype');
  9. var discriminator = require('../services/model/discriminator');
  10. var util = require('util');
  11. var utils = require('../utils');
  12. var getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;
  13. var MongooseDocumentArray;
  14. var Subdocument;
  15. /**
  16. * SubdocsArray SchemaType constructor
  17. *
  18. * @param {String} key
  19. * @param {Schema} schema
  20. * @param {Object} options
  21. * @inherits SchemaArray
  22. * @api public
  23. */
  24. function DocumentArray(key, schema, options) {
  25. var EmbeddedDocument = _createConstructor(schema, options);
  26. EmbeddedDocument.prototype.$basePath = key;
  27. ArrayType.call(this, key, EmbeddedDocument, options);
  28. this.schema = schema;
  29. this.$isMongooseDocumentArray = true;
  30. var fn = this.defaultValue;
  31. if (!('defaultValue' in this) || fn !== void 0) {
  32. this.default(function() {
  33. var arr = fn.call(this);
  34. if (!Array.isArray(arr)) {
  35. arr = [arr];
  36. }
  37. // Leave it up to `cast()` to convert this to a documentarray
  38. return arr;
  39. });
  40. }
  41. }
  42. /**
  43. * This schema type's name, to defend against minifiers that mangle
  44. * function names.
  45. *
  46. * @api public
  47. */
  48. DocumentArray.schemaName = 'DocumentArray';
  49. /*!
  50. * Inherits from ArrayType.
  51. */
  52. DocumentArray.prototype = Object.create(ArrayType.prototype);
  53. DocumentArray.prototype.constructor = DocumentArray;
  54. /*!
  55. * Ignore
  56. */
  57. function _createConstructor(schema, options) {
  58. Subdocument || (Subdocument = require('../types/embedded'));
  59. // compile an embedded document for this schema
  60. function EmbeddedDocument() {
  61. Subdocument.apply(this, arguments);
  62. }
  63. EmbeddedDocument.prototype = Object.create(Subdocument.prototype);
  64. EmbeddedDocument.prototype.$__setSchema(schema);
  65. EmbeddedDocument.schema = schema;
  66. EmbeddedDocument.prototype.constructor = EmbeddedDocument;
  67. EmbeddedDocument.$isArraySubdocument = true;
  68. // apply methods
  69. for (var i in schema.methods) {
  70. EmbeddedDocument.prototype[i] = schema.methods[i];
  71. }
  72. // apply statics
  73. for (i in schema.statics) {
  74. EmbeddedDocument[i] = schema.statics[i];
  75. }
  76. for (i in EventEmitter.prototype) {
  77. EmbeddedDocument[i] = EventEmitter.prototype[i];
  78. }
  79. EmbeddedDocument.options = options;
  80. return EmbeddedDocument;
  81. }
  82. /*!
  83. * Ignore
  84. */
  85. DocumentArray.prototype.discriminator = function(name, schema) {
  86. if (typeof name === 'function') {
  87. name = utils.getFunctionName(name);
  88. }
  89. schema = discriminator(this.casterConstructor, name, schema);
  90. var EmbeddedDocument = _createConstructor(schema);
  91. EmbeddedDocument.baseCasterConstructor = this.casterConstructor;
  92. try {
  93. Object.defineProperty(EmbeddedDocument, 'name', {
  94. value: name
  95. });
  96. } catch (error) {
  97. // Ignore error, only happens on old versions of node
  98. }
  99. this.casterConstructor.discriminators[name] = EmbeddedDocument;
  100. return this.casterConstructor.discriminators[name];
  101. };
  102. /**
  103. * Performs local validations first, then validations on each embedded doc
  104. *
  105. * @api private
  106. */
  107. DocumentArray.prototype.doValidate = function(array, fn, scope, options) {
  108. // lazy load
  109. MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
  110. var _this = this;
  111. SchemaType.prototype.doValidate.call(this, array, function(err) {
  112. if (err) {
  113. return fn(err);
  114. }
  115. var count = array && array.length;
  116. var error;
  117. if (!count) {
  118. return fn();
  119. }
  120. if (options && options.updateValidator) {
  121. return fn();
  122. }
  123. if (!array.isMongooseDocumentArray) {
  124. array = new MongooseDocumentArray(array, _this.path, scope);
  125. }
  126. // handle sparse arrays, do not use array.forEach which does not
  127. // iterate over sparse elements yet reports array.length including
  128. // them :(
  129. function callback(err) {
  130. if (err) {
  131. error = err;
  132. }
  133. --count || fn(error);
  134. }
  135. for (var i = 0, len = count; i < len; ++i) {
  136. // sidestep sparse entries
  137. var doc = array[i];
  138. if (!doc) {
  139. --count || fn(error);
  140. continue;
  141. }
  142. // If you set the array index directly, the doc might not yet be
  143. // a full fledged mongoose subdoc, so make it into one.
  144. if (!(doc instanceof Subdocument)) {
  145. doc = array[i] = new _this.casterConstructor(doc, array, undefined,
  146. undefined, i);
  147. }
  148. doc.$__validate(callback);
  149. }
  150. }, scope);
  151. };
  152. /**
  153. * Performs local validations first, then validations on each embedded doc.
  154. *
  155. * ####Note:
  156. *
  157. * This method ignores the asynchronous validators.
  158. *
  159. * @return {MongooseError|undefined}
  160. * @api private
  161. */
  162. DocumentArray.prototype.doValidateSync = function(array, scope) {
  163. var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
  164. if (schemaTypeError) {
  165. return schemaTypeError;
  166. }
  167. var count = array && array.length,
  168. resultError = null;
  169. if (!count) {
  170. return;
  171. }
  172. // handle sparse arrays, do not use array.forEach which does not
  173. // iterate over sparse elements yet reports array.length including
  174. // them :(
  175. for (var i = 0, len = count; i < len; ++i) {
  176. // only first error
  177. if (resultError) {
  178. break;
  179. }
  180. // sidestep sparse entries
  181. var doc = array[i];
  182. if (!doc) {
  183. continue;
  184. }
  185. // If you set the array index directly, the doc might not yet be
  186. // a full fledged mongoose subdoc, so make it into one.
  187. if (!(doc instanceof Subdocument)) {
  188. doc = array[i] = new this.casterConstructor(doc, array, undefined,
  189. undefined, i);
  190. }
  191. var subdocValidateError = doc.validateSync();
  192. if (subdocValidateError) {
  193. resultError = subdocValidateError;
  194. }
  195. }
  196. return resultError;
  197. };
  198. /**
  199. * Casts contents
  200. *
  201. * @param {Object} value
  202. * @param {Document} document that triggers the casting
  203. * @api private
  204. */
  205. DocumentArray.prototype.cast = function(value, doc, init, prev, options) {
  206. // lazy load
  207. MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
  208. var selected;
  209. var subdoc;
  210. var i;
  211. var _opts = { transform: false, virtuals: false };
  212. if (!Array.isArray(value)) {
  213. // gh-2442 mark whole array as modified if we're initializing a doc from
  214. // the db and the path isn't an array in the document
  215. if (!!doc && init) {
  216. doc.markModified(this.path);
  217. }
  218. return this.cast([value], doc, init, prev);
  219. }
  220. if (!(value && value.isMongooseDocumentArray) &&
  221. (!options || !options.skipDocumentArrayCast)) {
  222. value = new MongooseDocumentArray(value, this.path, doc);
  223. if (prev && prev._handlers) {
  224. for (var key in prev._handlers) {
  225. doc.removeListener(key, prev._handlers[key]);
  226. }
  227. }
  228. } else if (value && value.isMongooseDocumentArray) {
  229. // We need to create a new array, otherwise change tracking will
  230. // update the old doc (gh-4449)
  231. value = new MongooseDocumentArray(value, this.path, doc);
  232. }
  233. i = value.length;
  234. while (i--) {
  235. if (!value[i]) {
  236. continue;
  237. }
  238. var Constructor = this.casterConstructor;
  239. if (Constructor.discriminators &&
  240. Constructor.schema &&
  241. Constructor.schema.options &&
  242. typeof value[i][Constructor.schema.options.discriminatorKey] === 'string') {
  243. if (Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]]) {
  244. Constructor = Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]];
  245. } else {
  246. var constructorByValue = getDiscriminatorByValue(Constructor, value[i][Constructor.schema.options.discriminatorKey]);
  247. if (constructorByValue) {
  248. Constructor = constructorByValue;
  249. }
  250. }
  251. }
  252. // Check if the document has a different schema (re gh-3701)
  253. if ((value[i].$__) &&
  254. value[i].schema !== Constructor.schema) {
  255. value[i] = value[i].toObject({ transform: false, virtuals: false });
  256. }
  257. if (!(value[i] instanceof Subdocument) && value[i]) {
  258. if (init) {
  259. if (doc) {
  260. selected || (selected = scopePaths(this, doc.$__.selected, init));
  261. } else {
  262. selected = true;
  263. }
  264. subdoc = new Constructor(null, value, true, selected, i);
  265. value[i] = subdoc.init(value[i]);
  266. } else {
  267. if (prev && (subdoc = prev.id(value[i]._id))) {
  268. subdoc = prev.id(value[i]._id);
  269. }
  270. if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) {
  271. // handle resetting doc with existing id and same data
  272. subdoc.set(value[i]);
  273. // if set() is hooked it will have no return value
  274. // see gh-746
  275. value[i] = subdoc;
  276. } else {
  277. try {
  278. subdoc = new Constructor(value[i], value, undefined,
  279. undefined, i);
  280. // if set() is hooked it will have no return value
  281. // see gh-746
  282. value[i] = subdoc;
  283. } catch (error) {
  284. var valueInErrorMessage = util.inspect(value[i]);
  285. throw new CastError('embedded', valueInErrorMessage,
  286. value._path, error);
  287. }
  288. }
  289. }
  290. }
  291. }
  292. return value;
  293. };
  294. /*!
  295. * Scopes paths selected in a query to this array.
  296. * Necessary for proper default application of subdocument values.
  297. *
  298. * @param {DocumentArray} array - the array to scope `fields` paths
  299. * @param {Object|undefined} fields - the root fields selected in the query
  300. * @param {Boolean|undefined} init - if we are being created part of a query result
  301. */
  302. function scopePaths(array, fields, init) {
  303. if (!(init && fields)) {
  304. return undefined;
  305. }
  306. var path = array.path + '.';
  307. var keys = Object.keys(fields);
  308. var i = keys.length;
  309. var selected = {};
  310. var hasKeys;
  311. var key;
  312. var sub;
  313. while (i--) {
  314. key = keys[i];
  315. if (key.indexOf(path) === 0) {
  316. sub = key.substring(path.length);
  317. if (sub === '$') {
  318. continue;
  319. }
  320. if (sub.indexOf('$.') === 0) {
  321. sub = sub.substr(2);
  322. }
  323. hasKeys || (hasKeys = true);
  324. selected[sub] = fields[key];
  325. }
  326. }
  327. return hasKeys && selected || undefined;
  328. }
  329. /*!
  330. * Module exports.
  331. */
  332. module.exports = DocumentArray;