gx
chenyc
2025-06-12 7b72ac13a83764a662159d4a49b7fffb90476ecb
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/* eslint no-func-assign: 1 */
 
/*!
 * Module dependencies.
 */
 
'use strict';
 
const Document = require('../document_provider')();
const EventEmitter = require('events').EventEmitter;
const ValidationError = require('../error/validation');
const immediate = require('../helpers/immediate');
const internalToObjectOptions = require('../options').internalToObjectOptions;
const get = require('../helpers/get');
const promiseOrCallback = require('../helpers/promiseOrCallback');
const util = require('util');
 
const documentArrayParent = require('../helpers/symbols').documentArrayParent;
const validatorErrorSymbol = require('../helpers/symbols').validatorErrorSymbol;
 
/**
 * EmbeddedDocument constructor.
 *
 * @param {Object} obj js object returned from the db
 * @param {MongooseDocumentArray} parentArr the parent array of this document
 * @param {Boolean} skipId
 * @inherits Document
 * @api private
 */
 
function EmbeddedDocument(obj, parentArr, skipId, fields, index) {
  const options = {};
  if (parentArr != null && parentArr.isMongooseDocumentArray) {
    this.__parentArray = parentArr;
    this[documentArrayParent] = parentArr.$parent();
  } else {
    this.__parentArray = undefined;
    this[documentArrayParent] = undefined;
  }
  this.$setIndex(index);
  this.$isDocumentArrayElement = true;
 
  if (this[documentArrayParent] != null) {
    options.defaults = this[documentArrayParent].$__.$options.defaults;
  }
 
  Document.call(this, obj, fields, skipId, options);
 
  const _this = this;
  this.on('isNew', function(val) {
    _this.isNew = val;
  });
 
  _this.on('save', function() {
    _this.constructor.emit('save', _this);
  });
}
 
/*!
 * Inherit from Document
 */
EmbeddedDocument.prototype = Object.create(Document.prototype);
EmbeddedDocument.prototype.constructor = EmbeddedDocument;
 
for (const i in EventEmitter.prototype) {
  EmbeddedDocument[i] = EventEmitter.prototype[i];
}
 
EmbeddedDocument.prototype.toBSON = function() {
  return this.toObject(internalToObjectOptions);
};
 
/*!
 * ignore
 */
 
EmbeddedDocument.prototype.$setIndex = function(index) {
  this.__index = index;
 
  if (get(this, '$__.validationError', null) != null) {
    const keys = Object.keys(this.$__.validationError.errors);
    for (const key of keys) {
      this.invalidate(key, this.$__.validationError.errors[key]);
    }
  }
};
 
/**
 * Marks the embedded doc modified.
 *
 * ####Example:
 *
 *     const doc = blogpost.comments.id(hexstring);
 *     doc.mixed.type = 'changed';
 *     doc.markModified('mixed.type');
 *
 * @param {String} path the path which changed
 * @api public
 * @receiver EmbeddedDocument
 */
 
EmbeddedDocument.prototype.markModified = function(path) {
  this.$__.activePaths.modify(path);
  if (!this.__parentArray) {
    return;
  }
 
  const pathToCheck = this.__parentArray.$path() + '.0.' + path;
  if (this.isNew && this.ownerDocument().$__isSelected(pathToCheck)) {
    // Mark the WHOLE parent array as modified
    // if this is a new document (i.e., we are initializing
    // a document),
    this.__parentArray._markModified();
  } else {
    this.__parentArray._markModified(this, path);
  }
};
 
/*!
 * ignore
 */
 
EmbeddedDocument.prototype.populate = function() {
  throw new Error('Mongoose does not support calling populate() on nested ' +
    'docs. Instead of `doc.arr[0].populate("path")`, use ' +
    '`doc.populate("arr.0.path")`');
};
 
/**
 * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3)
 *
 * ####NOTE:
 *
 * _This is a no-op. Does not actually save the doc to the db._
 *
 * @param {Function} [fn]
 * @return {Promise} resolved Promise
 * @api private
 */
 
EmbeddedDocument.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 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
 */
 
EmbeddedDocument.prototype.$__save = function(fn) {
  return immediate(() => fn(null, this));
};
 
/*!
 * Registers remove event listeners for triggering
 * on subdocuments.
 *
 * @param {EmbeddedDocument} 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);
}
 
/*!
 * no-op for hooks
 */
 
EmbeddedDocument.prototype.$__remove = function(cb) {
  if (cb == null) {
    return;
  }
  return cb(null, this);
};
 
/**
 * Removes the subdocument from its parent array.
 *
 * @param {Object} [options]
 * @param {Function} [fn]
 * @api public
 */
 
EmbeddedDocument.prototype.remove = function(options, fn) {
  if (typeof options === 'function' && !fn) {
    fn = options;
    options = undefined;
  }
  if (!this.__parentArray || (options && options.noop)) {
    this.$__remove(fn);
    return this;
  }
 
  let _id;
  if (!this.willRemove) {
    _id = this._doc._id;
    if (!_id) {
      throw new Error('For your own good, Mongoose does not know ' +
          'how to remove an EmbeddedDocument that has no _id');
    }
    this.__parentArray.pull({ _id: _id });
    this.willRemove = true;
    registerRemoveListener(this);
  }
 
  this.$__remove(fn);
 
  return this;
};
 
/**
 * Override #update method of parent documents.
 * @api private
 */
 
EmbeddedDocument.prototype.update = function() {
  throw new Error('The #update method is not available on EmbeddedDocuments');
};
 
/**
 * Helper for console.log
 *
 * @api public
 */
 
EmbeddedDocument.prototype.inspect = function() {
  return this.toObject({
    transform: false,
    virtuals: false,
    flattenDecimals: false
  });
};
 
if (util.inspect.custom) {
  /*!
  * Avoid Node deprecation warning DEP0079
  */
 
  EmbeddedDocument.prototype[util.inspect.custom] = EmbeddedDocument.prototype.inspect;
}
 
/**
 * Marks a path as invalid, causing validation to fail.
 *
 * @param {String} path the field to invalidate
 * @param {String|Error} err error which states the reason `path` was invalid
 * @return {Boolean}
 * @api public
 */
 
EmbeddedDocument.prototype.invalidate = function(path, err, val) {
  Document.prototype.invalidate.call(this, path, err, val);
 
  if (!this[documentArrayParent] || this.__index == null) {
    if (err[validatorErrorSymbol] || err instanceof ValidationError) {
      return this.ownerDocument().$__.validationError;
    }
    throw err;
  }
 
  const index = this.__index;
  const parentPath = this.__parentArray.$path();
  const fullPath = [parentPath, index, path].join('.');
  this[documentArrayParent].invalidate(fullPath, err, val);
 
  return this.ownerDocument().$__.validationError;
};
 
/**
 * Marks a path as valid, removing existing validation errors.
 *
 * @param {String} path the field to mark as valid
 * @api private
 * @method $markValid
 * @receiver EmbeddedDocument
 */
 
EmbeddedDocument.prototype.$markValid = function(path) {
  if (!this[documentArrayParent]) {
    return;
  }
 
  const index = this.__index;
  if (typeof index !== 'undefined') {
    const parentPath = this.__parentArray.$path();
    const fullPath = [parentPath, index, path].join('.');
    this[documentArrayParent].$markValid(fullPath);
  }
};
 
/*!
 * ignore
 */
 
EmbeddedDocument.prototype.$ignore = function(path) {
  Document.prototype.$ignore.call(this, path);
 
  if (!this[documentArrayParent]) {
    return;
  }
 
  const index = this.__index;
  if (typeof index !== 'undefined') {
    const parentPath = this.__parentArray.$path();
    const fullPath = [parentPath, index, path].join('.');
    this[documentArrayParent].$ignore(fullPath);
  }
};
 
/**
 * Checks if a path is invalid
 *
 * @param {String} path the field to check
 * @api private
 * @method $isValid
 * @receiver EmbeddedDocument
 */
 
EmbeddedDocument.prototype.$isValid = function(path) {
  const index = this.__index;
  if (typeof index !== 'undefined' && this[documentArrayParent]) {
    return !this[documentArrayParent].$__.validationError ||
      !this[documentArrayParent].$__.validationError.errors[this.$__fullPath(path)];
  }
 
  return true;
};
 
/**
 * Returns the top level document of this sub-document.
 *
 * @return {Document}
 */
 
EmbeddedDocument.prototype.ownerDocument = function() {
  if (this.$__.ownerDocument) {
    return this.$__.ownerDocument;
  }
 
  let parent = this[documentArrayParent];
  if (!parent) {
    return this;
  }
 
  while (parent[documentArrayParent] || parent.$__parent) {
    parent = parent[documentArrayParent] || parent.$__parent;
  }
 
  this.$__.ownerDocument = parent;
  return this.$__.ownerDocument;
};
 
/**
 * Returns the full path to this document. If optional `path` is passed, it is appended to the full path.
 *
 * @param {String} [path]
 * @return {String}
 * @api private
 * @method $__fullPath
 * @memberOf EmbeddedDocument
 * @instance
 */
 
EmbeddedDocument.prototype.$__fullPath = function(path) {
  if (!this.$__.fullPath) {
    let parent = this;
    if (!parent[documentArrayParent]) {
      return path;
    }
 
    const paths = [];
    while (parent[documentArrayParent] || parent.$__parent) {
      if (parent[documentArrayParent]) {
        paths.unshift(parent.__parentArray.$path());
      } else {
        paths.unshift(parent.$basePath);
      }
      parent = parent[documentArrayParent] || parent.$__parent;
    }
 
    this.$__.fullPath = paths.join('.');
 
    if (!this.$__.ownerDocument) {
      // optimization
      this.$__.ownerDocument = parent;
    }
  }
 
  return path
    ? this.$__.fullPath + '.' + path
    : this.$__.fullPath;
};
 
/**
 * Returns this sub-documents parent document.
 *
 * @api public
 */
 
EmbeddedDocument.prototype.parent = function() {
  return this[documentArrayParent];
};
 
/**
 * Returns this sub-documents parent document.
 *
 * @api public
 */
 
EmbeddedDocument.prototype.$parent = EmbeddedDocument.prototype.parent;
 
/**
 * Returns this sub-documents parent array.
 *
 * @api public
 */
 
EmbeddedDocument.prototype.parentArray = function() {
  return this.__parentArray;
};
 
/*!
 * Module exports.
 */
 
module.exports = EmbeddedDocument;