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