/
subdocument.js
272 lines (225 loc) · 6.53 KB
/
subdocument.js
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
'use strict';
const Document = require('../document');
const immediate = require('../helpers/immediate');
const internalToObjectOptions = require('../options').internalToObjectOptions;
const utils = require('../utils');
const documentArrayParent = require('../helpers/symbols').documentArrayParent;
module.exports = Subdocument;
/**
* Subdocument constructor.
*
* @inherits Document
* @api private
*/
function Subdocument(value, fields, parent, skipId, options) {
this.$isSingleNested = true;
const hasPriorDoc = options != null && options.priorDoc;
let initedPaths = null;
if (hasPriorDoc) {
this._doc = Object.assign({}, options.priorDoc._doc);
delete this._doc[this.schema.options.discriminatorKey];
initedPaths = Object.keys(options.priorDoc._doc || {}).
filter(key => key !== this.schema.options.discriminatorKey);
}
if (parent != null) {
// If setting a nested path, should copy isNew from parent re: gh-7048
options = Object.assign({}, options, { isNew: parent.isNew });
}
Document.call(this, value, fields, skipId, options);
if (hasPriorDoc) {
for (const key of initedPaths) {
if (!this.$__.activePaths.states.modify[key] &&
!this.$__.activePaths.states.default[key] &&
!this.$__.$setCalled.has(key)) {
delete this._doc[key];
}
}
}
}
Subdocument.prototype = Object.create(Document.prototype);
Subdocument.prototype.toBSON = function() {
return this.toObject(internalToObjectOptions);
};
/**
* Used as a stub for middleware
*
* ####NOTE:
*
* _This is a no-op. Does not actually save the doc to the db._
*
* @param {Function} [fn]
* @return {Promise} resolved Promise
* @api private
*/
Subdocument.prototype.save = function(options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
options = options || {};
if (!options.suppressWarning) {
console.warn('mongoose: calling `save()` on a subdoc does **not** save ' +
'the document to MongoDB, it only runs save middleware. ' +
'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' +
'if you\'re sure this behavior is right for your app.');
}
return utils.promiseOrCallback(fn, cb => {
this.$__save(cb);
});
};
/**
* Used as a stub for middleware
*
* ####NOTE:
*
* _This is a no-op. Does not actually save the doc to the db._
*
* @param {Function} [fn]
* @method $__save
* @api private
*/
Subdocument.prototype.$__save = function(fn) {
return immediate(() => fn(null, this));
};
Subdocument.prototype.$isValid = function(path) {
if (this.$parent && this.$basePath) {
return this.$parent.$isValid([this.$basePath, path].join('.'));
}
return Document.prototype.$isValid.call(this, path);
};
Subdocument.prototype.markModified = function(path) {
Document.prototype.markModified.call(this, path);
if (this.$parent && this.$basePath) {
if (this.$parent.isDirectModified(this.$basePath)) {
return;
}
this.$parent.markModified([this.$basePath, path].join('.'), this);
}
};
Subdocument.prototype.isModified = function(paths, modifiedPaths) {
if (this.$parent && this.$basePath) {
paths = (Array.isArray(paths) ? paths : paths.split(' ')).
map(p => [this.$basePath, p].join('.'));
return this.$parent.isModified(paths, modifiedPaths);
}
return Document.prototype.isModified(paths, modifiedPaths);
};
/**
* Marks a path as valid, removing existing validation errors.
*
* @param {String} path the field to mark as valid
* @api private
* @method $markValid
* @receiver Subdocument
*/
Subdocument.prototype.$markValid = function(path) {
Document.prototype.$markValid.call(this, path);
if (this.$parent && this.$basePath) {
this.$parent.$markValid([this.$basePath, path].join('.'));
}
};
/*!
* ignore
*/
Subdocument.prototype.invalidate = function(path, err, val) {
// Hack: array subdocuments' validationError is equal to the owner doc's,
// so validating an array subdoc gives the top-level doc back. Temporary
// workaround for #5208 so we don't have circular errors.
if (err !== this.ownerDocument().$__.validationError) {
Document.prototype.invalidate.call(this, path, err, val);
}
if (this.$parent && this.$basePath) {
this.$parent.invalidate([this.$basePath, path].join('.'), err, val);
} else if (err.kind === 'cast' || err.name === 'CastError') {
throw err;
}
};
/*!
* ignore
*/
Subdocument.prototype.$ignore = function(path) {
Document.prototype.$ignore.call(this, path);
if (this.$parent && this.$basePath) {
this.$parent.$ignore([this.$basePath, path].join('.'));
}
};
/**
* Returns the top level document of this sub-document.
*
* @return {Document}
*/
Subdocument.prototype.ownerDocument = function() {
if (this.$__.ownerDocument) {
return this.$__.ownerDocument;
}
let parent = this.$parent;
if (!parent) {
return this;
}
while (parent.$parent || parent[documentArrayParent]) {
parent = parent.$parent || parent[documentArrayParent];
}
this.$__.ownerDocument = parent;
return this.$__.ownerDocument;
};
/**
* Returns this sub-documents parent document.
*
* @api public
*/
Subdocument.prototype.parent = function() {
return this.$parent;
};
/*!
* no-op for hooks
*/
Subdocument.prototype.$__remove = function(cb) {
return cb(null, this);
};
/**
* Null-out this subdoc
*
* @param {Object} [options]
* @param {Function} [callback] optional callback for compatibility with Document.prototype.remove
*/
Subdocument.prototype.remove = function(options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
registerRemoveListener(this);
// If removing entire doc, no need to remove subdoc
if (!options || !options.noop) {
this.$parent.set(this.$basePath, null);
}
if (typeof callback === 'function') {
callback(null);
}
};
/*!
* ignore
*/
Subdocument.prototype.populate = function() {
throw new Error('Mongoose does not support calling populate() on nested ' +
'docs. Instead of `doc.nested.populate("path")`, use ' +
'`doc.populate("nested.path")`');
};
/*!
* Registers remove event listeners for triggering
* on subdocuments.
*
* @param {Subdocument} sub
* @api private
*/
function registerRemoveListener(sub) {
let owner = sub.ownerDocument();
function emitRemove() {
owner.removeListener('save', emitRemove);
owner.removeListener('remove', emitRemove);
sub.emit('remove', sub);
sub.constructor.emit('remove', sub);
owner = sub = null;
}
owner.on('save', emitRemove);
owner.on('remove', emitRemove);
}