PageRenderTime 38ms CodeModel.GetById 10ms app.highlight 22ms RepoModel.GetById 1ms app.codeStats 1ms

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