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
|
/**
* Module dependencies.
*/
var MongooseArray = require('./array')
, driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native'
, ObjectId = require(driver + '/objectid')
, ObjectIdSchema = require('../schema/objectid');
/**
* Array of embedded documents
* Values always have to be passed to the constructor to initialize, since
* otherwise MongooseArray#push will mark the array as modified to the parent.
*
* @param {Array} values
* @param {String} key path
* @param {Document} parent document
* @api private
* @see http://bit.ly/f6CnZU
*/
function MongooseDocumentArray (values, path, doc) {
var arr = [];
arr.push.apply(arr, values);
arr.__proto__ = MongooseDocumentArray.prototype;
arr._atomics = {};
arr.validators = [];
arr._path = path;
if (doc) {
arr._parent = doc;
arr._schema = doc.schema.path(path);
doc.on('save', arr.notify('save'));
doc.on('isNew', arr.notify('isNew'));
}
return arr;
};
/**
* Inherits from MongooseArray
*/
MongooseDocumentArray.prototype.__proto__ = MongooseArray.prototype;
/**
* Overrides cast
*
* @api private
*/
MongooseDocumentArray.prototype._cast = function (value) {
var doc = new this._schema.caster(value, this);
return doc;
};
/**
* Filters items by id
*
* @param {Object} id
* @api public
*/
MongooseDocumentArray.prototype.id = function (id) {
try {
var casted = ObjectId.toString(ObjectIdSchema.prototype.cast.call({}, id));
} catch (e) {
var casted = null;
}
for (var i = 0, l = this.length; i < l; i++) {
if (!(this[i].get('_id') instanceof ObjectId)) {
if (String(id) == this[i].get('_id').toString())
return this[i];
} else {
if (casted == this[i].get('_id').toString())
return this[i];
}
}
return null;
};
/**
* Returns an Array and converts any Document
* members toObject.
*
* @return {Array}
* @api public
*/
MongooseDocumentArray.prototype.toObject = function () {
return this.map(function (doc) {
return doc && doc.toObject() || null;
});
};
/**
* Helper for console.log
*
* @api public
*/
MongooseDocumentArray.prototype.inspect = function () {
return '[' + this.map(function (doc) {
return doc && doc.inspect() || 'null';
}).join('\n') + ']';
};
/**
* Create fn that notifies all child docs of event.
*
* @param {String} event
* @api private
*/
MongooseDocumentArray.prototype.notify = function notify (event) {
var self = this;
return function notify (val) {
var i = self.length;
while (i--) {
self[i].emit(event, val);
}
}
}
/**
* Module exports.
*/
module.exports = MongooseDocumentArray;
|