@datanimbus/mongoose 6.13.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/.eslintrc.js +232 -0
  2. package/.mocharc.yml +4 -0
  3. package/LICENSE.md +22 -0
  4. package/README.md +387 -0
  5. package/SECURITY.md +1 -0
  6. package/browser.js +8 -0
  7. package/dist/browser.umd.js +2 -0
  8. package/index.js +63 -0
  9. package/lgtm.yml +12 -0
  10. package/lib/aggregate.js +1164 -0
  11. package/lib/browser.js +158 -0
  12. package/lib/browserDocument.js +101 -0
  13. package/lib/cast/boolean.js +32 -0
  14. package/lib/cast/date.js +41 -0
  15. package/lib/cast/decimal128.js +36 -0
  16. package/lib/cast/number.js +42 -0
  17. package/lib/cast/objectid.js +29 -0
  18. package/lib/cast/string.js +37 -0
  19. package/lib/cast.js +418 -0
  20. package/lib/collection.js +311 -0
  21. package/lib/connection.js +1574 -0
  22. package/lib/connectionstate.js +26 -0
  23. package/lib/cursor/AggregationCursor.js +380 -0
  24. package/lib/cursor/ChangeStream.js +154 -0
  25. package/lib/cursor/QueryCursor.js +538 -0
  26. package/lib/document.js +4771 -0
  27. package/lib/document_provider.js +30 -0
  28. package/lib/driver.js +15 -0
  29. package/lib/drivers/SPEC.md +4 -0
  30. package/lib/drivers/browser/ReadPreference.js +7 -0
  31. package/lib/drivers/browser/binary.js +14 -0
  32. package/lib/drivers/browser/decimal128.js +7 -0
  33. package/lib/drivers/browser/index.js +16 -0
  34. package/lib/drivers/browser/objectid.js +29 -0
  35. package/lib/drivers/node-mongodb-native/ReadPreference.js +47 -0
  36. package/lib/drivers/node-mongodb-native/binary.js +10 -0
  37. package/lib/drivers/node-mongodb-native/collection.js +460 -0
  38. package/lib/drivers/node-mongodb-native/connection.js +166 -0
  39. package/lib/drivers/node-mongodb-native/decimal128.js +7 -0
  40. package/lib/drivers/node-mongodb-native/index.js +12 -0
  41. package/lib/drivers/node-mongodb-native/objectid.js +16 -0
  42. package/lib/error/browserMissingSchema.js +28 -0
  43. package/lib/error/bulkWriteError.js +41 -0
  44. package/lib/error/cast.js +158 -0
  45. package/lib/error/disconnected.js +33 -0
  46. package/lib/error/divergentArray.js +38 -0
  47. package/lib/error/eachAsyncMultiError.js +41 -0
  48. package/lib/error/index.js +228 -0
  49. package/lib/error/messages.js +47 -0
  50. package/lib/error/missingSchema.js +31 -0
  51. package/lib/error/mongooseError.js +13 -0
  52. package/lib/error/notFound.js +45 -0
  53. package/lib/error/objectExpected.js +30 -0
  54. package/lib/error/objectParameter.js +30 -0
  55. package/lib/error/overwriteModel.js +30 -0
  56. package/lib/error/parallelSave.js +30 -0
  57. package/lib/error/parallelValidate.js +31 -0
  58. package/lib/error/serverSelection.js +61 -0
  59. package/lib/error/setOptionError.js +101 -0
  60. package/lib/error/strict.js +33 -0
  61. package/lib/error/strictPopulate.js +29 -0
  62. package/lib/error/syncIndexes.js +30 -0
  63. package/lib/error/validation.js +103 -0
  64. package/lib/error/validator.js +99 -0
  65. package/lib/error/version.js +36 -0
  66. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +39 -0
  67. package/lib/helpers/aggregate/stringifyFunctionOperators.js +50 -0
  68. package/lib/helpers/arrayDepth.js +33 -0
  69. package/lib/helpers/clone.js +177 -0
  70. package/lib/helpers/common.js +127 -0
  71. package/lib/helpers/cursor/eachAsync.js +222 -0
  72. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +16 -0
  73. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +12 -0
  74. package/lib/helpers/discriminator/getConstructor.js +26 -0
  75. package/lib/helpers/discriminator/getDiscriminatorByValue.js +28 -0
  76. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +27 -0
  77. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +64 -0
  78. package/lib/helpers/document/applyDefaults.js +128 -0
  79. package/lib/helpers/document/cleanModifiedSubpaths.js +35 -0
  80. package/lib/helpers/document/compile.js +237 -0
  81. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +50 -0
  82. package/lib/helpers/document/handleSpreadDoc.js +35 -0
  83. package/lib/helpers/each.js +25 -0
  84. package/lib/helpers/error/combinePathErrors.js +22 -0
  85. package/lib/helpers/firstKey.js +8 -0
  86. package/lib/helpers/get.js +65 -0
  87. package/lib/helpers/getConstructorName.js +16 -0
  88. package/lib/helpers/getDefaultBulkwriteResult.js +27 -0
  89. package/lib/helpers/getFunctionName.js +10 -0
  90. package/lib/helpers/immediate.js +16 -0
  91. package/lib/helpers/indexes/applySchemaCollation.js +13 -0
  92. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +14 -0
  93. package/lib/helpers/indexes/getRelatedIndexes.js +59 -0
  94. package/lib/helpers/indexes/isDefaultIdIndex.js +18 -0
  95. package/lib/helpers/indexes/isIndexEqual.js +96 -0
  96. package/lib/helpers/indexes/isTextIndex.js +16 -0
  97. package/lib/helpers/isAsyncFunction.js +9 -0
  98. package/lib/helpers/isBsonType.js +16 -0
  99. package/lib/helpers/isMongooseObject.js +22 -0
  100. package/lib/helpers/isObject.js +16 -0
  101. package/lib/helpers/isPromise.js +6 -0
  102. package/lib/helpers/isSimpleValidator.js +22 -0
  103. package/lib/helpers/model/applyDefaultsToPOJO.js +52 -0
  104. package/lib/helpers/model/applyHooks.js +149 -0
  105. package/lib/helpers/model/applyMethods.js +70 -0
  106. package/lib/helpers/model/applyStaticHooks.js +71 -0
  107. package/lib/helpers/model/applyStatics.js +13 -0
  108. package/lib/helpers/model/castBulkWrite.js +240 -0
  109. package/lib/helpers/model/discriminator.js +218 -0
  110. package/lib/helpers/model/pushNestedArrayPaths.js +15 -0
  111. package/lib/helpers/once.js +12 -0
  112. package/lib/helpers/parallelLimit.js +55 -0
  113. package/lib/helpers/path/parentPaths.js +18 -0
  114. package/lib/helpers/path/setDottedPath.js +33 -0
  115. package/lib/helpers/pluralize.js +94 -0
  116. package/lib/helpers/populate/SkipPopulateValue.js +10 -0
  117. package/lib/helpers/populate/assignRawDocsToIdStructure.js +124 -0
  118. package/lib/helpers/populate/assignVals.js +337 -0
  119. package/lib/helpers/populate/createPopulateQueryFilter.js +97 -0
  120. package/lib/helpers/populate/getModelsMapForPopulate.js +756 -0
  121. package/lib/helpers/populate/getSchemaTypes.js +233 -0
  122. package/lib/helpers/populate/getVirtual.js +72 -0
  123. package/lib/helpers/populate/leanPopulateMap.js +7 -0
  124. package/lib/helpers/populate/lookupLocalFields.js +40 -0
  125. package/lib/helpers/populate/markArraySubdocsPopulated.js +47 -0
  126. package/lib/helpers/populate/modelNamesFromRefPath.js +68 -0
  127. package/lib/helpers/populate/removeDeselectedForeignField.js +31 -0
  128. package/lib/helpers/populate/validateRef.js +19 -0
  129. package/lib/helpers/printJestWarning.js +21 -0
  130. package/lib/helpers/printStrictQueryWarning.js +11 -0
  131. package/lib/helpers/processConnectionOptions.js +65 -0
  132. package/lib/helpers/projection/applyProjection.js +77 -0
  133. package/lib/helpers/projection/hasIncludedChildren.js +41 -0
  134. package/lib/helpers/projection/isDefiningProjection.js +18 -0
  135. package/lib/helpers/projection/isExclusive.js +35 -0
  136. package/lib/helpers/projection/isInclusive.js +38 -0
  137. package/lib/helpers/projection/isNestedProjection.js +8 -0
  138. package/lib/helpers/projection/isPathExcluded.js +40 -0
  139. package/lib/helpers/projection/isPathSelectedInclusive.js +28 -0
  140. package/lib/helpers/projection/isSubpath.js +14 -0
  141. package/lib/helpers/projection/parseProjection.js +33 -0
  142. package/lib/helpers/promiseOrCallback.js +55 -0
  143. package/lib/helpers/query/applyGlobalOption.js +29 -0
  144. package/lib/helpers/query/applyQueryMiddleware.js +79 -0
  145. package/lib/helpers/query/cast$expr.js +282 -0
  146. package/lib/helpers/query/castFilterPath.js +54 -0
  147. package/lib/helpers/query/castUpdate.js +560 -0
  148. package/lib/helpers/query/completeMany.js +52 -0
  149. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +90 -0
  150. package/lib/helpers/query/handleImmutable.js +28 -0
  151. package/lib/helpers/query/hasDollarKeys.js +23 -0
  152. package/lib/helpers/query/isOperator.js +14 -0
  153. package/lib/helpers/query/sanitizeFilter.js +38 -0
  154. package/lib/helpers/query/sanitizeProjection.js +14 -0
  155. package/lib/helpers/query/selectPopulatedFields.js +49 -0
  156. package/lib/helpers/query/trusted.js +13 -0
  157. package/lib/helpers/query/validOps.js +24 -0
  158. package/lib/helpers/query/wrapThunk.js +31 -0
  159. package/lib/helpers/schema/addAutoId.js +7 -0
  160. package/lib/helpers/schema/applyBuiltinPlugins.js +12 -0
  161. package/lib/helpers/schema/applyPlugins.js +55 -0
  162. package/lib/helpers/schema/applyWriteConcern.js +30 -0
  163. package/lib/helpers/schema/cleanPositionalOperators.js +12 -0
  164. package/lib/helpers/schema/getIndexes.js +164 -0
  165. package/lib/helpers/schema/getKeysInSchemaOrder.js +28 -0
  166. package/lib/helpers/schema/getPath.js +37 -0
  167. package/lib/helpers/schema/handleIdOption.js +20 -0
  168. package/lib/helpers/schema/handleTimestampOption.js +24 -0
  169. package/lib/helpers/schema/idGetter.js +32 -0
  170. package/lib/helpers/schema/merge.js +28 -0
  171. package/lib/helpers/schematype/handleImmutable.js +50 -0
  172. package/lib/helpers/setDefaultsOnInsert.js +132 -0
  173. package/lib/helpers/specialProperties.js +3 -0
  174. package/lib/helpers/symbols.js +20 -0
  175. package/lib/helpers/timers.js +3 -0
  176. package/lib/helpers/timestamps/setDocumentTimestamps.js +26 -0
  177. package/lib/helpers/timestamps/setupTimestamps.js +101 -0
  178. package/lib/helpers/topology/allServersUnknown.js +12 -0
  179. package/lib/helpers/topology/isAtlas.js +31 -0
  180. package/lib/helpers/topology/isSSLError.js +16 -0
  181. package/lib/helpers/update/applyTimestampsToChildren.js +193 -0
  182. package/lib/helpers/update/applyTimestampsToUpdate.js +117 -0
  183. package/lib/helpers/update/castArrayFilters.js +109 -0
  184. package/lib/helpers/update/modifiedPaths.js +33 -0
  185. package/lib/helpers/update/moveImmutableProperties.js +53 -0
  186. package/lib/helpers/update/removeUnusedArrayFilters.js +32 -0
  187. package/lib/helpers/update/updatedPathsByArrayFilter.js +27 -0
  188. package/lib/helpers/updateValidators.js +249 -0
  189. package/lib/index.js +1338 -0
  190. package/lib/internal.js +46 -0
  191. package/lib/model.js +5474 -0
  192. package/lib/options/PopulateOptions.js +36 -0
  193. package/lib/options/SchemaArrayOptions.js +78 -0
  194. package/lib/options/SchemaBufferOptions.js +38 -0
  195. package/lib/options/SchemaDateOptions.js +71 -0
  196. package/lib/options/SchemaDocumentArrayOptions.js +68 -0
  197. package/lib/options/SchemaMapOptions.js +43 -0
  198. package/lib/options/SchemaNumberOptions.js +101 -0
  199. package/lib/options/SchemaObjectIdOptions.js +64 -0
  200. package/lib/options/SchemaStringOptions.js +138 -0
  201. package/lib/options/SchemaSubdocumentOptions.js +42 -0
  202. package/lib/options/SchemaTypeOptions.js +244 -0
  203. package/lib/options/VirtualOptions.js +164 -0
  204. package/lib/options/propertyOptions.js +8 -0
  205. package/lib/options/removeOptions.js +14 -0
  206. package/lib/options/saveOptions.js +14 -0
  207. package/lib/options.js +15 -0
  208. package/lib/plugins/index.js +7 -0
  209. package/lib/plugins/removeSubdocs.js +31 -0
  210. package/lib/plugins/saveSubdocs.js +66 -0
  211. package/lib/plugins/sharding.js +83 -0
  212. package/lib/plugins/trackTransaction.js +92 -0
  213. package/lib/plugins/validateBeforeSave.js +45 -0
  214. package/lib/promise_provider.js +49 -0
  215. package/lib/query.js +5982 -0
  216. package/lib/queryhelpers.js +353 -0
  217. package/lib/schema/DocumentArrayElement.js +100 -0
  218. package/lib/schema/SubdocumentPath.js +369 -0
  219. package/lib/schema/array.js +663 -0
  220. package/lib/schema/boolean.js +267 -0
  221. package/lib/schema/buffer.js +269 -0
  222. package/lib/schema/date.js +404 -0
  223. package/lib/schema/decimal128.js +210 -0
  224. package/lib/schema/documentarray.js +598 -0
  225. package/lib/schema/index.js +39 -0
  226. package/lib/schema/map.js +84 -0
  227. package/lib/schema/mixed.js +132 -0
  228. package/lib/schema/number.js +438 -0
  229. package/lib/schema/objectid.js +295 -0
  230. package/lib/schema/operators/bitwise.js +38 -0
  231. package/lib/schema/operators/exists.js +12 -0
  232. package/lib/schema/operators/geospatial.js +107 -0
  233. package/lib/schema/operators/helpers.js +32 -0
  234. package/lib/schema/operators/text.js +39 -0
  235. package/lib/schema/operators/type.js +20 -0
  236. package/lib/schema/string.js +694 -0
  237. package/lib/schema/symbols.js +5 -0
  238. package/lib/schema/uuid.js +334 -0
  239. package/lib/schema.js +2665 -0
  240. package/lib/schematype.js +1727 -0
  241. package/lib/statemachine.js +207 -0
  242. package/lib/types/ArraySubdocument.js +189 -0
  243. package/lib/types/DocumentArray/index.js +113 -0
  244. package/lib/types/DocumentArray/isMongooseDocumentArray.js +5 -0
  245. package/lib/types/DocumentArray/methods/index.js +383 -0
  246. package/lib/types/array/index.js +116 -0
  247. package/lib/types/array/isMongooseArray.js +5 -0
  248. package/lib/types/array/methods/index.js +1014 -0
  249. package/lib/types/buffer.js +277 -0
  250. package/lib/types/decimal128.js +13 -0
  251. package/lib/types/index.js +20 -0
  252. package/lib/types/map.js +354 -0
  253. package/lib/types/objectid.js +41 -0
  254. package/lib/types/subdocument.js +432 -0
  255. package/lib/utils.js +1011 -0
  256. package/lib/validoptions.js +36 -0
  257. package/lib/virtualtype.js +175 -0
  258. package/package.json +164 -0
  259. package/scripts/build-browser.js +18 -0
  260. package/scripts/create-tarball.js +7 -0
  261. package/scripts/generateSearch.js +154 -0
  262. package/scripts/tsc-diagnostics-check.js +15 -0
  263. package/tools/auth.js +31 -0
  264. package/tools/repl.js +35 -0
  265. package/tools/sharded.js +46 -0
  266. package/tsconfig.json +9 -0
  267. package/types/aggregate.d.ts +174 -0
  268. package/types/augmentations.d.ts +9 -0
  269. package/types/callback.d.ts +8 -0
  270. package/types/collection.d.ts +44 -0
  271. package/types/connection.d.ts +242 -0
  272. package/types/cursor.d.ts +62 -0
  273. package/types/document.d.ts +266 -0
  274. package/types/error.d.ts +138 -0
  275. package/types/expressions.d.ts +2936 -0
  276. package/types/helpers.d.ts +32 -0
  277. package/types/index.d.ts +627 -0
  278. package/types/indexes.d.ts +98 -0
  279. package/types/inferschematype.d.ts +228 -0
  280. package/types/middlewares.d.ts +32 -0
  281. package/types/models.d.ts +488 -0
  282. package/types/mongooseoptions.d.ts +206 -0
  283. package/types/pipelinestage.d.ts +297 -0
  284. package/types/populate.d.ts +45 -0
  285. package/types/query.d.ts +659 -0
  286. package/types/schemaoptions.d.ts +231 -0
  287. package/types/schematypes.d.ts +478 -0
  288. package/types/session.d.ts +36 -0
  289. package/types/types.d.ts +104 -0
  290. package/types/utility.d.ts +43 -0
  291. package/types/validation.d.ts +34 -0
  292. package/types/virtuals.d.ts +14 -0
@@ -0,0 +1,4771 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const EventEmitter = require('events').EventEmitter;
8
+ const InternalCache = require('./internal');
9
+ const MongooseError = require('./error/index');
10
+ const MixedSchema = require('./schema/mixed');
11
+ const ObjectExpectedError = require('./error/objectExpected');
12
+ const ObjectParameterError = require('./error/objectParameter');
13
+ const ParallelValidateError = require('./error/parallelValidate');
14
+ const Schema = require('./schema');
15
+ const StrictModeError = require('./error/strict');
16
+ const ValidationError = require('./error/validation');
17
+ const ValidatorError = require('./error/validator');
18
+ const $__hasIncludedChildren = require('./helpers/projection/hasIncludedChildren');
19
+ const promiseOrCallback = require('./helpers/promiseOrCallback');
20
+ const applyDefaults = require('./helpers/document/applyDefaults');
21
+ const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
22
+ const compile = require('./helpers/document/compile').compile;
23
+ const defineKey = require('./helpers/document/compile').defineKey;
24
+ const flatten = require('./helpers/common').flatten;
25
+ const get = require('./helpers/get');
26
+ const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
27
+ const getKeysInSchemaOrder = require('./helpers/schema/getKeysInSchemaOrder');
28
+ const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');
29
+ const immediate = require('./helpers/immediate');
30
+ const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
31
+ const isExclusive = require('./helpers/projection/isExclusive');
32
+ const inspect = require('util').inspect;
33
+ const internalToObjectOptions = require('./options').internalToObjectOptions;
34
+ const markArraySubdocsPopulated = require('./helpers/populate/markArraySubdocsPopulated');
35
+ const mpath = require('mpath');
36
+ const queryhelpers = require('./queryhelpers');
37
+ const utils = require('./utils');
38
+ const isPromise = require('./helpers/isPromise');
39
+
40
+ const clone = utils.clone;
41
+ const deepEqual = utils.deepEqual;
42
+ const isMongooseObject = utils.isMongooseObject;
43
+
44
+ const arrayAtomicsBackupSymbol = require('./helpers/symbols').arrayAtomicsBackupSymbol;
45
+ const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
46
+ const documentArrayParent = require('./helpers/symbols').documentArrayParent;
47
+ const documentIsModified = require('./helpers/symbols').documentIsModified;
48
+ const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths;
49
+ const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
50
+ const getSymbol = require('./helpers/symbols').getSymbol;
51
+ const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
52
+ const scopeSymbol = require('./helpers/symbols').scopeSymbol;
53
+ const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
54
+ const parentPaths = require('./helpers/path/parentPaths');
55
+
56
+ let DocumentArray;
57
+ let MongooseArray;
58
+ let Embedded;
59
+
60
+ const specialProperties = utils.specialProperties;
61
+
62
+ /**
63
+ * The core Mongoose document constructor. You should not call this directly,
64
+ * the Mongoose [Model constructor](./api/model.html#Model) calls this for you.
65
+ *
66
+ * @param {Object} obj the values to set
67
+ * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
68
+ * @param {Object} [options] various configuration options for the document
69
+ * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document.
70
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
71
+ * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose.
72
+ * @event `save`: Emitted when the document is successfully saved
73
+ * @api private
74
+ */
75
+
76
+ function Document(obj, fields, skipId, options) {
77
+ if (typeof skipId === 'object' && skipId != null) {
78
+ options = skipId;
79
+ skipId = options.skipId;
80
+ }
81
+ options = Object.assign({}, options);
82
+
83
+ // Support `browserDocument.js` syntax
84
+ if (this.$__schema == null) {
85
+ const _schema = utils.isObject(fields) && !fields.instanceOfSchema ?
86
+ new Schema(fields) :
87
+ fields;
88
+ this.$__setSchema(_schema);
89
+ fields = skipId;
90
+ skipId = options;
91
+ options = arguments[4] || {};
92
+ }
93
+
94
+ this.$__ = new InternalCache();
95
+
96
+ // Avoid setting `isNew` to `true`, because it is `true` by default
97
+ if (options.isNew != null && options.isNew !== true) {
98
+ this.$isNew = options.isNew;
99
+ }
100
+
101
+ if (options.priorDoc != null) {
102
+ this.$__.priorDoc = options.priorDoc;
103
+ }
104
+
105
+ if (skipId) {
106
+ this.$__.skipId = skipId;
107
+ }
108
+
109
+ if (obj != null && typeof obj !== 'object') {
110
+ throw new ObjectParameterError(obj, 'obj', 'Document');
111
+ }
112
+
113
+ let defaults = true;
114
+ if (options.defaults !== undefined) {
115
+ this.$__.defaults = options.defaults;
116
+ defaults = options.defaults;
117
+ }
118
+
119
+ const schema = this.$__schema;
120
+
121
+ if (typeof fields === 'boolean' || fields === 'throw') {
122
+ if (fields !== true) {
123
+ this.$__.strictMode = fields;
124
+ }
125
+ fields = undefined;
126
+ } else if (schema.options.strict !== true) {
127
+ this.$__.strictMode = schema.options.strict;
128
+ }
129
+
130
+ const requiredPaths = schema.requiredPaths(true);
131
+ for (const path of requiredPaths) {
132
+ this.$__.activePaths.require(path);
133
+ }
134
+
135
+ let exclude = null;
136
+
137
+ // determine if this doc is a result of a query with
138
+ // excluded fields
139
+ if (utils.isPOJO(fields) && Object.keys(fields).length > 0) {
140
+ exclude = isExclusive(fields);
141
+ this.$__.selected = fields;
142
+ this.$__.exclude = exclude;
143
+ }
144
+
145
+ const hasIncludedChildren = exclude === false && fields ?
146
+ $__hasIncludedChildren(fields) :
147
+ null;
148
+
149
+ if (this._doc == null) {
150
+ this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false);
151
+
152
+ // By default, defaults get applied **before** setting initial values
153
+ // Re: gh-6155
154
+ if (defaults) {
155
+ applyDefaults(this, fields, exclude, hasIncludedChildren, true, null);
156
+ }
157
+ }
158
+ if (obj) {
159
+ // Skip set hooks
160
+ if (this.$__original_set) {
161
+ this.$__original_set(obj, undefined, true, options);
162
+ } else {
163
+ this.$set(obj, undefined, true, options);
164
+ }
165
+
166
+ if (obj instanceof Document) {
167
+ this.$isNew = obj.$isNew;
168
+ }
169
+ }
170
+
171
+ // Function defaults get applied **after** setting initial values so they
172
+ // see the full doc rather than an empty one, unless they opt out.
173
+ // Re: gh-3781, gh-6155
174
+ if (options.willInit && defaults) {
175
+ if (options.skipDefaults) {
176
+ this.$__.skipDefaults = options.skipDefaults;
177
+ }
178
+ } else if (defaults) {
179
+ applyDefaults(this, fields, exclude, hasIncludedChildren, false, options.skipDefaults);
180
+ }
181
+
182
+ if (!this.$__.strictMode && obj) {
183
+ const _this = this;
184
+ const keys = Object.keys(this._doc);
185
+
186
+ keys.forEach(function(key) {
187
+ // Avoid methods, virtuals, existing fields, and `$` keys. The latter is to avoid overwriting
188
+ // Mongoose internals.
189
+ if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && !key.startsWith('$')) {
190
+ defineKey({ prop: key, subprops: null, prototype: _this });
191
+ }
192
+ });
193
+ }
194
+
195
+ applyQueue(this);
196
+ }
197
+
198
+ Document.prototype.$isMongooseDocumentPrototype = true;
199
+
200
+ /**
201
+ * Boolean flag specifying if the document is new. If you create a document
202
+ * using `new`, this document will be considered "new". `$isNew` is how
203
+ * Mongoose determines whether `save()` should use `insertOne()` to create
204
+ * a new document or `updateOne()` to update an existing document.
205
+ *
206
+ * #### Example:
207
+ *
208
+ * const user = new User({ name: 'John Smith' });
209
+ * user.$isNew; // true
210
+ *
211
+ * await user.save(); // Sends an `insertOne` to MongoDB
212
+ *
213
+ * On the other hand, if you load an existing document from the database
214
+ * using `findOne()` or another [query operation](/docs/queries.html),
215
+ * `$isNew` will be false.
216
+ *
217
+ * #### Example:
218
+ *
219
+ * const user = await User.findOne({ name: 'John Smith' });
220
+ * user.$isNew; // false
221
+ *
222
+ * Mongoose sets `$isNew` to `false` immediately after `save()` succeeds.
223
+ * That means Mongoose sets `$isNew` to false **before** `post('save')` hooks run.
224
+ * In `post('save')` hooks, `$isNew` will be `false` if `save()` succeeded.
225
+ *
226
+ * #### Example:
227
+ *
228
+ * userSchema.post('save', function() {
229
+ * this.$isNew; // false
230
+ * });
231
+ * await User.create({ name: 'John Smith' });
232
+ *
233
+ * For subdocuments, `$isNew` is true if either the parent has `$isNew` set,
234
+ * or if you create a new subdocument.
235
+ *
236
+ * #### Example:
237
+ *
238
+ * // Assume `Group` has a document array `users`
239
+ * const group = await Group.findOne();
240
+ * group.users[0].$isNew; // false
241
+ *
242
+ * group.users.push({ name: 'John Smith' });
243
+ * group.users[1].$isNew; // true
244
+ *
245
+ * @api public
246
+ * @property $isNew
247
+ * @memberOf Document
248
+ * @instance
249
+ */
250
+
251
+ Object.defineProperty(Document.prototype, 'isNew', {
252
+ get: function() {
253
+ return this.$isNew;
254
+ },
255
+ set: function(value) {
256
+ this.$isNew = value;
257
+ }
258
+ });
259
+
260
+ /**
261
+ * Hash containing current validation errors.
262
+ *
263
+ * @api public
264
+ * @property errors
265
+ * @memberOf Document
266
+ * @instance
267
+ */
268
+
269
+ Object.defineProperty(Document.prototype, 'errors', {
270
+ get: function() {
271
+ return this.$errors;
272
+ },
273
+ set: function(value) {
274
+ this.$errors = value;
275
+ }
276
+ });
277
+
278
+ /*!
279
+ * ignore
280
+ */
281
+
282
+ Document.prototype.$isNew = true;
283
+
284
+ /*!
285
+ * Document exposes the NodeJS event emitter API, so you can use
286
+ * `on`, `once`, etc.
287
+ */
288
+ utils.each(
289
+ ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
290
+ 'removeAllListeners', 'addListener'],
291
+ function(emitterFn) {
292
+ Document.prototype[emitterFn] = function() {
293
+ // Delay creating emitter until necessary because emitters take up a lot of memory,
294
+ // especially for subdocuments.
295
+ if (!this.$__.emitter) {
296
+ if (emitterFn === 'emit') {
297
+ return;
298
+ }
299
+ this.$__.emitter = new EventEmitter();
300
+ this.$__.emitter.setMaxListeners(0);
301
+ }
302
+ return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
303
+ };
304
+ Document.prototype[`$${emitterFn}`] = Document.prototype[emitterFn];
305
+ });
306
+
307
+ Document.prototype.constructor = Document;
308
+
309
+ for (const i in EventEmitter.prototype) {
310
+ Document[i] = EventEmitter.prototype[i];
311
+ }
312
+
313
+ /**
314
+ * The document's internal schema.
315
+ *
316
+ * @api private
317
+ * @property schema
318
+ * @memberOf Document
319
+ * @instance
320
+ */
321
+
322
+ Document.prototype.$__schema;
323
+
324
+ /**
325
+ * The document's schema.
326
+ *
327
+ * @api public
328
+ * @property schema
329
+ * @memberOf Document
330
+ * @instance
331
+ */
332
+
333
+ Document.prototype.schema;
334
+
335
+ /**
336
+ * Empty object that you can use for storing properties on the document. This
337
+ * is handy for passing data to middleware without conflicting with Mongoose
338
+ * internals.
339
+ *
340
+ * #### Example:
341
+ *
342
+ * schema.pre('save', function() {
343
+ * // Mongoose will set `isNew` to `false` if `save()` succeeds
344
+ * this.$locals.wasNew = this.isNew;
345
+ * });
346
+ *
347
+ * schema.post('save', function() {
348
+ * // Prints true if `isNew` was set before `save()`
349
+ * console.log(this.$locals.wasNew);
350
+ * });
351
+ *
352
+ * @api public
353
+ * @property $locals
354
+ * @memberOf Document
355
+ * @instance
356
+ */
357
+
358
+ Object.defineProperty(Document.prototype, '$locals', {
359
+ configurable: false,
360
+ enumerable: false,
361
+ get: function() {
362
+ if (this.$__.locals == null) {
363
+ this.$__.locals = {};
364
+ }
365
+ return this.$__.locals;
366
+ },
367
+ set: function(v) {
368
+ this.$__.locals = v;
369
+ }
370
+ });
371
+
372
+ /**
373
+ * Legacy alias for `$isNew`.
374
+ *
375
+ * @api public
376
+ * @property isNew
377
+ * @memberOf Document
378
+ * @see $isNew #document_Document-$isNew
379
+ * @instance
380
+ */
381
+
382
+ Document.prototype.isNew;
383
+
384
+ /**
385
+ * Set this property to add additional query filters when Mongoose saves this document and `isNew` is false.
386
+ *
387
+ * #### Example:
388
+ *
389
+ * // Make sure `save()` never updates a soft deleted document.
390
+ * schema.pre('save', function() {
391
+ * this.$where = { isDeleted: false };
392
+ * });
393
+ *
394
+ * @api public
395
+ * @property $where
396
+ * @memberOf Document
397
+ * @instance
398
+ */
399
+
400
+ Object.defineProperty(Document.prototype, '$where', {
401
+ configurable: false,
402
+ enumerable: false,
403
+ writable: true
404
+ });
405
+
406
+ /**
407
+ * The string version of this documents _id.
408
+ *
409
+ * #### Note:
410
+ *
411
+ * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time.
412
+ *
413
+ * new Schema({ name: String }, { id: false });
414
+ *
415
+ * @api public
416
+ * @see Schema options /docs/guide.html#options
417
+ * @property id
418
+ * @memberOf Document
419
+ * @instance
420
+ */
421
+
422
+ Document.prototype.id;
423
+
424
+ /**
425
+ * Hash containing current validation $errors.
426
+ *
427
+ * @api public
428
+ * @property $errors
429
+ * @memberOf Document
430
+ * @instance
431
+ */
432
+
433
+ Document.prototype.$errors;
434
+
435
+ /**
436
+ * A string containing the current operation that Mongoose is executing
437
+ * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
438
+ *
439
+ * #### Example:
440
+ *
441
+ * const doc = new Model({ name: 'test' });
442
+ * doc.$op; // null
443
+ *
444
+ * const promise = doc.save();
445
+ * doc.$op; // 'save'
446
+ *
447
+ * await promise;
448
+ * doc.$op; // null
449
+ *
450
+ * @api public
451
+ * @property $op
452
+ * @memberOf Document
453
+ * @instance
454
+ */
455
+
456
+ Object.defineProperty(Document.prototype, '$op', {
457
+ get: function() {
458
+ return this.$__.op || null;
459
+ },
460
+ set: function(value) {
461
+ this.$__.op = value;
462
+ }
463
+ });
464
+
465
+ /*!
466
+ * ignore
467
+ */
468
+
469
+ function $applyDefaultsToNested(val, path, doc) {
470
+ if (val == null) {
471
+ return;
472
+ }
473
+
474
+ const paths = Object.keys(doc.$__schema.paths);
475
+ const plen = paths.length;
476
+
477
+ const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.');
478
+
479
+ for (let i = 0; i < plen; ++i) {
480
+ let curPath = '';
481
+ const p = paths[i];
482
+
483
+ if (!p.startsWith(path + '.')) {
484
+ continue;
485
+ }
486
+
487
+ const type = doc.$__schema.paths[p];
488
+ const pieces = type.splitPath().slice(pathPieces.length);
489
+ const len = pieces.length;
490
+
491
+ if (type.defaultValue === void 0) {
492
+ continue;
493
+ }
494
+
495
+ let cur = val;
496
+
497
+ for (let j = 0; j < len; ++j) {
498
+ if (cur == null) {
499
+ break;
500
+ }
501
+
502
+ const piece = pieces[j];
503
+
504
+ if (j === len - 1) {
505
+ if (cur[piece] !== void 0) {
506
+ break;
507
+ }
508
+
509
+ try {
510
+ const def = type.getDefault(doc, false);
511
+ if (def !== void 0) {
512
+ cur[piece] = def;
513
+ }
514
+ } catch (err) {
515
+ doc.invalidate(path + '.' + curPath, err);
516
+ break;
517
+ }
518
+
519
+ break;
520
+ }
521
+
522
+ curPath += (!curPath.length ? '' : '.') + piece;
523
+
524
+ cur[piece] = cur[piece] || {};
525
+ cur = cur[piece];
526
+ }
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Builds the default doc structure
532
+ *
533
+ * @param {Object} obj
534
+ * @param {Object} [fields]
535
+ * @param {Boolean} [skipId]
536
+ * @param {Boolean} [exclude]
537
+ * @param {Object} [hasIncludedChildren]
538
+ * @api private
539
+ * @method $__buildDoc
540
+ * @memberOf Document
541
+ * @instance
542
+ */
543
+
544
+ Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) {
545
+ const doc = {};
546
+
547
+ const paths = Object.keys(this.$__schema.paths).
548
+ // Don't build up any paths that are underneath a map, we don't know
549
+ // what the keys will be
550
+ filter(p => !p.includes('$*'));
551
+ const plen = paths.length;
552
+ let ii = 0;
553
+
554
+ for (; ii < plen; ++ii) {
555
+ const p = paths[ii];
556
+
557
+ if (p === '_id') {
558
+ if (skipId) {
559
+ continue;
560
+ }
561
+ if (obj && '_id' in obj) {
562
+ continue;
563
+ }
564
+ }
565
+
566
+ const path = this.$__schema.paths[p].splitPath();
567
+ const len = path.length;
568
+ const last = len - 1;
569
+ let curPath = '';
570
+ let doc_ = doc;
571
+ let included = false;
572
+
573
+ for (let i = 0; i < len; ++i) {
574
+ const piece = path[i];
575
+
576
+ if (!curPath.length) {
577
+ curPath = piece;
578
+ } else {
579
+ curPath += '.' + piece;
580
+ }
581
+
582
+ // support excluding intermediary levels
583
+ if (exclude === true) {
584
+ if (curPath in fields) {
585
+ break;
586
+ }
587
+ } else if (exclude === false && fields && !included) {
588
+ if (curPath in fields) {
589
+ included = true;
590
+ } else if (!hasIncludedChildren[curPath]) {
591
+ break;
592
+ }
593
+ }
594
+
595
+ if (i < last) {
596
+ doc_ = doc_[piece] || (doc_[piece] = {});
597
+ }
598
+ }
599
+ }
600
+
601
+ this._doc = doc;
602
+ };
603
+
604
+ /*!
605
+ * Converts to POJO when you use the document for querying
606
+ */
607
+
608
+ Document.prototype.toBSON = function() {
609
+ return this.toObject(internalToObjectOptions);
610
+ };
611
+
612
+ /**
613
+ * Initializes the document without setters or marking anything modified.
614
+ *
615
+ * Called internally after a document is returned from mongodb. Normally,
616
+ * you do **not** need to call this function on your own.
617
+ *
618
+ * This function triggers `init` [middleware](/docs/middleware.html).
619
+ * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous).
620
+ *
621
+ * @param {Object} doc document returned by mongo
622
+ * @param {Object} [opts]
623
+ * @param {Function} [fn]
624
+ * @api public
625
+ * @memberOf Document
626
+ * @instance
627
+ */
628
+
629
+ Document.prototype.init = function(doc, opts, fn) {
630
+ if (typeof opts === 'function') {
631
+ fn = opts;
632
+ opts = null;
633
+ }
634
+
635
+ this.$__init(doc, opts);
636
+
637
+ if (fn) {
638
+ fn(null, this);
639
+ }
640
+
641
+ return this;
642
+ };
643
+
644
+ /**
645
+ * Alias for [`.init`](#document_Document-init)
646
+ *
647
+ * @api public
648
+ */
649
+
650
+ Document.prototype.$init = function() {
651
+ return this.constructor.prototype.init.apply(this, arguments);
652
+ };
653
+
654
+ /**
655
+ * Internal "init" function
656
+ *
657
+ * @param {Document} doc
658
+ * @param {Object} [opts]
659
+ * @returns {Document} this
660
+ * @api private
661
+ */
662
+
663
+ Document.prototype.$__init = function(doc, opts) {
664
+ this.$isNew = false;
665
+ opts = opts || {};
666
+
667
+ // handle docs with populated paths
668
+ // If doc._id is not null or undefined
669
+ if (doc._id != null && opts.populated && opts.populated.length) {
670
+ const id = String(doc._id);
671
+ for (const item of opts.populated) {
672
+ if (item.isVirtual) {
673
+ this.$populated(item.path, utils.getValue(item.path, doc), item);
674
+ } else {
675
+ this.$populated(item.path, item._docs[id], item);
676
+ }
677
+
678
+ if (item._childDocs == null) {
679
+ continue;
680
+ }
681
+ for (const child of item._childDocs) {
682
+ if (child == null || child.$__ == null) {
683
+ continue;
684
+ }
685
+ child.$__.parent = this;
686
+ }
687
+ item._childDocs = [];
688
+ }
689
+ }
690
+
691
+ init(this, doc, this._doc, opts);
692
+
693
+ markArraySubdocsPopulated(this, opts.populated);
694
+
695
+ this.$emit('init', this);
696
+ this.constructor.emit('init', this);
697
+
698
+ const hasIncludedChildren = this.$__.exclude === false && this.$__.selected ?
699
+ $__hasIncludedChildren(this.$__.selected) :
700
+ null;
701
+
702
+ applyDefaults(this, this.$__.selected, this.$__.exclude, hasIncludedChildren, false, this.$__.skipDefaults);
703
+
704
+ return this;
705
+ };
706
+
707
+ /**
708
+ * Init helper.
709
+ *
710
+ * @param {Object} self document instance
711
+ * @param {Object} obj raw mongodb doc
712
+ * @param {Object} doc object we are initializing
713
+ * @param {Object} [opts] Optional Options
714
+ * @param {Boolean} [opts.setters] Call `applySetters` instead of `cast`
715
+ * @param {String} [prefix] Prefix to add to each path
716
+ * @api private
717
+ */
718
+
719
+ function init(self, obj, doc, opts, prefix) {
720
+ prefix = prefix || '';
721
+
722
+ if (obj.$__ != null) {
723
+ obj = obj._doc;
724
+ }
725
+ const keys = Object.keys(obj);
726
+ const len = keys.length;
727
+ let schemaType;
728
+ let path;
729
+ let i;
730
+ let index = 0;
731
+ const strict = self.$__.strictMode;
732
+ const docSchema = self.$__schema;
733
+
734
+ while (index < len) {
735
+ _init(index++);
736
+ }
737
+
738
+ function _init(index) {
739
+ i = keys[index];
740
+ // avoid prototype pollution
741
+ if (i === '__proto__' || i === 'constructor') {
742
+ return;
743
+ }
744
+ path = prefix ? prefix + i : i;
745
+ schemaType = docSchema.path(path);
746
+
747
+ // Should still work if not a model-level discriminator, but should not be
748
+ // necessary. This is *only* to catch the case where we queried using the
749
+ // base model and the discriminated model has a projection
750
+ if (docSchema.$isRootDiscriminator && !self.$__isSelected(path)) {
751
+ return;
752
+ }
753
+
754
+ const value = obj[i];
755
+ if (!schemaType && utils.isPOJO(value)) {
756
+ // assume nested object
757
+ if (!doc[i]) {
758
+ doc[i] = {};
759
+ if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
760
+ self[i] = doc[i];
761
+ }
762
+ }
763
+ init(self, value, doc[i], opts, path + '.');
764
+ } else if (!schemaType) {
765
+ doc[i] = value;
766
+ if (!strict && !prefix) {
767
+ self[i] = value;
768
+ }
769
+ } else {
770
+ // Retain order when overwriting defaults
771
+ if (doc.hasOwnProperty(i) && value !== void 0) {
772
+ delete doc[i];
773
+ }
774
+ if (value === null) {
775
+ doc[i] = schemaType._castNullish(null);
776
+ } else if (value !== undefined) {
777
+ const wasPopulated = value.$__ == null ? null : value.$__.wasPopulated;
778
+
779
+ if (schemaType && !wasPopulated) {
780
+ try {
781
+ if (opts && opts.setters) {
782
+ // Call applySetters with `init = false` because otherwise setters are a noop
783
+ const overrideInit = false;
784
+ doc[i] = schemaType.applySetters(value, self, overrideInit);
785
+ } else {
786
+ doc[i] = schemaType.cast(value, self, true);
787
+ }
788
+ } catch (e) {
789
+ self.invalidate(e.path, new ValidatorError({
790
+ path: e.path,
791
+ message: e.message,
792
+ type: 'cast',
793
+ value: e.value,
794
+ reason: e
795
+ }));
796
+ }
797
+ } else {
798
+ doc[i] = value;
799
+ }
800
+ }
801
+ // mark as hydrated
802
+ if (!self.$isModified(path)) {
803
+ self.$__.activePaths.init(path);
804
+ }
805
+ }
806
+ }
807
+ }
808
+
809
+ /**
810
+ * Sends an update command with this document `_id` as the query selector.
811
+ *
812
+ * #### Example:
813
+ *
814
+ * weirdCar.update({ $inc: { wheels:1 } }, { w: 1 }, callback);
815
+ *
816
+ * #### Valid options:
817
+ *
818
+ * - same as in [Model.update](#model_Model-update)
819
+ *
820
+ * @see Model.update #model_Model-update
821
+ * @param {...Object} ops
822
+ * @param {Object} [options]
823
+ * @param {Function} [callback]
824
+ * @return {Query} this
825
+ * @api public
826
+ * @memberOf Document
827
+ * @instance
828
+ */
829
+
830
+ Document.prototype.update = function update() {
831
+ const args = [...arguments];
832
+ args.unshift({ _id: this._id });
833
+ const query = this.constructor.update.apply(this.constructor, args);
834
+
835
+ if (this.$session() != null) {
836
+ if (!('session' in query.options)) {
837
+ query.options.session = this.$session();
838
+ }
839
+ }
840
+
841
+ return query;
842
+ };
843
+
844
+ /**
845
+ * Sends an updateOne command with this document `_id` as the query selector.
846
+ *
847
+ * #### Example:
848
+ *
849
+ * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
850
+ *
851
+ * #### Valid options:
852
+ *
853
+ * - same as in [Model.updateOne](#model_Model-updateOne)
854
+ *
855
+ * @see Model.updateOne #model_Model-updateOne
856
+ * @param {Object} doc
857
+ * @param {Object} [options] optional see [`Query.prototype.setOptions()`](https://mongoosejs.com/docs/api/query.html#query_Query-setOptions)
858
+ * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api/query.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
859
+ * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](https://mongoosejs.com/docs/guide.html#strict)
860
+ * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
861
+ * @param {Function} [callback]
862
+ * @return {Query}
863
+ * @api public
864
+ * @memberOf Document
865
+ * @instance
866
+ */
867
+
868
+ Document.prototype.updateOne = function updateOne(doc, options, callback) {
869
+ const query = this.constructor.updateOne({ _id: this._id }, doc, options);
870
+ const self = this;
871
+ query.pre(function queryPreUpdateOne(cb) {
872
+ self.constructor._middleware.execPre('updateOne', self, [self], cb);
873
+ });
874
+ query.post(function queryPostUpdateOne(cb) {
875
+ self.constructor._middleware.execPost('updateOne', self, [self], {}, cb);
876
+ });
877
+
878
+ if (this.$session() != null) {
879
+ if (!('session' in query.options)) {
880
+ query.options.session = this.$session();
881
+ }
882
+ }
883
+
884
+ if (callback != null) {
885
+ return query.exec(callback);
886
+ }
887
+
888
+ return query;
889
+ };
890
+
891
+ /**
892
+ * Sends a replaceOne command with this document `_id` as the query selector.
893
+ *
894
+ * #### Valid options:
895
+ *
896
+ * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model-replaceOne)
897
+ *
898
+ * @see Model.replaceOne #model_Model-replaceOne
899
+ * @param {Object} doc
900
+ * @param {Object} [options]
901
+ * @param {Function} [callback]
902
+ * @return {Query}
903
+ * @api public
904
+ * @memberOf Document
905
+ * @instance
906
+ */
907
+
908
+ Document.prototype.replaceOne = function replaceOne() {
909
+ const args = [...arguments];
910
+ args.unshift({ _id: this._id });
911
+ return this.constructor.replaceOne.apply(this.constructor, args);
912
+ };
913
+
914
+ /**
915
+ * Getter/setter around the session associated with this document. Used to
916
+ * automatically set `session` if you `save()` a doc that you got from a
917
+ * query with an associated session.
918
+ *
919
+ * #### Example:
920
+ *
921
+ * const session = MyModel.startSession();
922
+ * const doc = await MyModel.findOne().session(session);
923
+ * doc.$session() === session; // true
924
+ * doc.$session(null);
925
+ * doc.$session() === null; // true
926
+ *
927
+ * If this is a top-level document, setting the session propagates to all child
928
+ * docs.
929
+ *
930
+ * @param {ClientSession} [session] overwrite the current session
931
+ * @return {ClientSession}
932
+ * @method $session
933
+ * @api public
934
+ * @memberOf Document
935
+ */
936
+
937
+ Document.prototype.$session = function $session(session) {
938
+ if (arguments.length === 0) {
939
+ if (this.$__.session != null && this.$__.session.hasEnded) {
940
+ this.$__.session = null;
941
+ return null;
942
+ }
943
+ return this.$__.session;
944
+ }
945
+
946
+ if (session != null && session.hasEnded) {
947
+ throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' +
948
+ 'called `endSession()` on the session you are passing to `$session()`.');
949
+ }
950
+
951
+ if (session == null && this.$__.session == null) {
952
+ return;
953
+ }
954
+
955
+ this.$__.session = session;
956
+
957
+ if (!this.$isSubdocument) {
958
+ const subdocs = this.$getAllSubdocs();
959
+ for (const child of subdocs) {
960
+ child.$session(session);
961
+ }
962
+ }
963
+
964
+ return session;
965
+ };
966
+
967
+ /**
968
+ * Getter/setter around whether this document will apply timestamps by
969
+ * default when using `save()` and `bulkSave()`.
970
+ *
971
+ * #### Example:
972
+ *
973
+ * const TestModel = mongoose.model('Test', new Schema({ name: String }, { timestamps: true }));
974
+ * const doc = new TestModel({ name: 'John Smith' });
975
+ *
976
+ * doc.$timestamps(); // true
977
+ *
978
+ * doc.$timestamps(false);
979
+ * await doc.save(); // Does **not** apply timestamps
980
+ *
981
+ * @param {Boolean} [value] overwrite the current session
982
+ * @return {Document|boolean|undefined} When used as a getter (no argument), a boolean will be returned indicating the timestamps option state or if unset "undefined" will be used, otherwise will return "this"
983
+ * @method $timestamps
984
+ * @api public
985
+ * @memberOf Document
986
+ */
987
+
988
+ Document.prototype.$timestamps = function $timestamps(value) {
989
+ if (arguments.length === 0) {
990
+ if (this.$__.timestamps != null) {
991
+ return this.$__.timestamps;
992
+ }
993
+
994
+ if (this.$__schema) {
995
+ return this.$__schema.options.timestamps;
996
+ }
997
+
998
+ return undefined;
999
+ }
1000
+
1001
+ const currentValue = this.$timestamps();
1002
+ if (value !== currentValue) {
1003
+ this.$__.timestamps = value;
1004
+ }
1005
+
1006
+ return this;
1007
+ };
1008
+
1009
+ /**
1010
+ * Overwrite all values in this document with the values of `obj`, except
1011
+ * for immutable properties. Behaves similarly to `set()`, except for it
1012
+ * unsets all properties that aren't in `obj`.
1013
+ *
1014
+ * @param {Object} obj the object to overwrite this document with
1015
+ * @method overwrite
1016
+ * @memberOf Document
1017
+ * @instance
1018
+ * @api public
1019
+ * @return {Document} this
1020
+ */
1021
+
1022
+ Document.prototype.overwrite = function overwrite(obj) {
1023
+ const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
1024
+
1025
+ for (const key of keys) {
1026
+ if (key === '_id') {
1027
+ continue;
1028
+ }
1029
+ // Explicitly skip version key
1030
+ if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) {
1031
+ continue;
1032
+ }
1033
+ if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) {
1034
+ continue;
1035
+ }
1036
+ this.$set(key, obj[key]);
1037
+ }
1038
+
1039
+ return this;
1040
+ };
1041
+
1042
+ /**
1043
+ * Alias for `set()`, used internally to avoid conflicts
1044
+ *
1045
+ * @param {String|Object} path path or object of key/vals to set
1046
+ * @param {Any} val the value to set
1047
+ * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
1048
+ * @param {Object} [options] optionally specify options that modify the behavior of the set
1049
+ * @param {Boolean} [options.merge=false] if true, setting a [nested path](/docs/subdocs.html#subdocuments-versus-nested-paths) will merge existing values rather than overwrite the whole object. So `doc.set('nested', { a: 1, b: 2 })` becomes `doc.set('nested.a', 1); doc.set('nested.b', 2);`
1050
+ * @return {Document} this
1051
+ * @method $set
1052
+ * @memberOf Document
1053
+ * @instance
1054
+ * @api public
1055
+ */
1056
+
1057
+ Document.prototype.$set = function $set(path, val, type, options) {
1058
+ if (utils.isPOJO(type)) {
1059
+ options = type;
1060
+ type = undefined;
1061
+ }
1062
+
1063
+ const merge = options && options.merge;
1064
+ const adhoc = type && type !== true;
1065
+ const constructing = type === true;
1066
+ let adhocs;
1067
+ let keys;
1068
+ let i = 0;
1069
+ let pathtype;
1070
+ let key;
1071
+ let prefix;
1072
+
1073
+ const strict = options && 'strict' in options
1074
+ ? options.strict
1075
+ : this.$__.strictMode;
1076
+
1077
+ if (adhoc) {
1078
+ adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
1079
+ adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options);
1080
+ }
1081
+
1082
+ if (path == null) {
1083
+ [path, val] = [val, path];
1084
+ } else if (typeof path !== 'string') {
1085
+ // new Document({ key: val })
1086
+ if (path instanceof Document) {
1087
+ if (path.$__isNested) {
1088
+ path = path.toObject();
1089
+ } else {
1090
+ // This ternary is to support gh-7898 (copying virtuals if same schema)
1091
+ // while not breaking gh-10819, which for some reason breaks if we use toObject()
1092
+ path = path.$__schema === this.$__schema
1093
+ ? applyVirtuals(path, { ...path._doc })
1094
+ : path._doc;
1095
+ }
1096
+ }
1097
+ if (path == null) {
1098
+ [path, val] = [val, path];
1099
+ }
1100
+
1101
+ prefix = val ? val + '.' : '';
1102
+ keys = getKeysInSchemaOrder(this.$__schema, path);
1103
+
1104
+ const len = keys.length;
1105
+
1106
+ // `_skipMinimizeTopLevel` is because we may have deleted the top-level
1107
+ // nested key to ensure key order.
1108
+ const _skipMinimizeTopLevel = options && options._skipMinimizeTopLevel || false;
1109
+ if (len === 0 && _skipMinimizeTopLevel) {
1110
+ delete options._skipMinimizeTopLevel;
1111
+ if (val) {
1112
+ this.$set(val, {});
1113
+ }
1114
+ return this;
1115
+ }
1116
+
1117
+ options = Object.assign({}, options, { _skipMinimizeTopLevel: false });
1118
+
1119
+ for (let i = 0; i < len; ++i) {
1120
+ key = keys[i];
1121
+ const pathName = prefix ? prefix + key : key;
1122
+ pathtype = this.$__schema.pathType(pathName);
1123
+ const valForKey = path[key];
1124
+
1125
+ // On initial set, delete any nested keys if we're going to overwrite
1126
+ // them to ensure we keep the user's key order.
1127
+ if (type === true &&
1128
+ !prefix &&
1129
+ valForKey != null &&
1130
+ pathtype === 'nested' &&
1131
+ this._doc[key] != null) {
1132
+ delete this._doc[key];
1133
+ }
1134
+
1135
+ if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') {
1136
+ this.$set(pathName, valForKey, constructing, Object.assign({}, options, { _skipMarkModified: true }));
1137
+ $applyDefaultsToNested(this.$get(pathName), pathName, this);
1138
+ continue;
1139
+ } else if (strict) {
1140
+ // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)
1141
+ if (constructing && valForKey === void 0 &&
1142
+ this.$get(pathName) !== void 0) {
1143
+ continue;
1144
+ }
1145
+
1146
+ if (pathtype === 'adhocOrUndefined') {
1147
+ pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
1148
+ }
1149
+
1150
+ if (pathtype === 'real' || pathtype === 'virtual') {
1151
+ this.$set(pathName, valForKey, constructing, options);
1152
+ } else if (pathtype === 'nested' && valForKey instanceof Document) {
1153
+ this.$set(pathName,
1154
+ valForKey.toObject({ transform: false }), constructing, options);
1155
+ } else if (strict === 'throw') {
1156
+ if (pathtype === 'nested') {
1157
+ throw new ObjectExpectedError(key, valForKey);
1158
+ } else {
1159
+ throw new StrictModeError(key);
1160
+ }
1161
+ } else if (pathtype === 'nested' && valForKey == null) {
1162
+ this.$set(pathName, valForKey, constructing, options);
1163
+ }
1164
+ } else if (valForKey !== void 0) {
1165
+ this.$set(pathName, valForKey, constructing, options);
1166
+ }
1167
+ }
1168
+
1169
+ // Ensure all properties are in correct order
1170
+ const orderedDoc = {};
1171
+ const orderedKeys = Object.keys(this.$__schema.tree);
1172
+ for (let i = 0, len = orderedKeys.length; i < len; ++i) {
1173
+ (key = orderedKeys[i]) &&
1174
+ (this._doc.hasOwnProperty(key)) &&
1175
+ (orderedDoc[key] = undefined);
1176
+ }
1177
+ this._doc = Object.assign(orderedDoc, this._doc);
1178
+
1179
+ return this;
1180
+ }
1181
+
1182
+ let pathType = this.$__schema.pathType(path);
1183
+ if (pathType === 'adhocOrUndefined') {
1184
+ pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true });
1185
+ }
1186
+
1187
+ // Assume this is a Mongoose document that was copied into a POJO using
1188
+ // `Object.assign()` or `{...doc}`
1189
+ val = handleSpreadDoc(val);
1190
+
1191
+ // if this doc is being constructed we should not trigger getters
1192
+ const priorVal = (() => {
1193
+ if (this.$__.priorDoc != null) {
1194
+ return this.$__.priorDoc.$__getValue(path);
1195
+ }
1196
+ if (constructing) {
1197
+ return void 0;
1198
+ }
1199
+ return this.$__getValue(path);
1200
+ })();
1201
+
1202
+ if (pathType === 'nested' && val) {
1203
+ if (typeof val === 'object' && val != null) {
1204
+ if (val.$__ != null) {
1205
+ val = val.toObject(internalToObjectOptions);
1206
+ }
1207
+ if (val == null) {
1208
+ this.invalidate(path, new MongooseError.CastError('Object', val, path));
1209
+ return this;
1210
+ }
1211
+ const wasModified = this.$isModified(path);
1212
+ const hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path);
1213
+ if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) {
1214
+ const initialVal = this.$__getValue(path);
1215
+ this.$__.savedState[path] = initialVal;
1216
+
1217
+ const keys = Object.keys(initialVal || {});
1218
+ for (const key of keys) {
1219
+ this.$__.savedState[path + '.' + key] = initialVal[key];
1220
+ }
1221
+ }
1222
+
1223
+ if (!merge) {
1224
+ this.$__setValue(path, null);
1225
+ cleanModifiedSubpaths(this, path);
1226
+ } else {
1227
+ return this.$set(val, path, constructing, options);
1228
+ }
1229
+
1230
+ const keys = getKeysInSchemaOrder(this.$__schema, val, path);
1231
+
1232
+ this.$__setValue(path, {});
1233
+ for (const key of keys) {
1234
+ this.$set(path + '.' + key, val[key], constructing, { ...options, _skipMarkModified: true });
1235
+ }
1236
+ if (priorVal != null &&
1237
+ (!wasModified || hasInitialVal) &&
1238
+ utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) {
1239
+ this.unmarkModified(path);
1240
+ } else {
1241
+ this.markModified(path);
1242
+ }
1243
+ return this;
1244
+ }
1245
+ this.invalidate(path, new MongooseError.CastError('Object', val, path));
1246
+ return this;
1247
+ }
1248
+
1249
+ let schema;
1250
+ const parts = path.indexOf('.') === -1 ? [path] : path.split('.');
1251
+
1252
+ // Might need to change path for top-level alias
1253
+ if (typeof this.$__schema.aliases[parts[0]] === 'string') {
1254
+ parts[0] = this.$__schema.aliases[parts[0]];
1255
+ }
1256
+
1257
+ if (pathType === 'adhocOrUndefined' && strict) {
1258
+ // check for roots that are Mixed types
1259
+ let mixed;
1260
+
1261
+ for (i = 0; i < parts.length; ++i) {
1262
+ const subpath = parts.slice(0, i + 1).join('.');
1263
+
1264
+ // If path is underneath a virtual, bypass everything and just set it.
1265
+ if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') {
1266
+ mpath.set(path, val, this);
1267
+ return this;
1268
+ }
1269
+
1270
+ schema = this.$__schema.path(subpath);
1271
+ if (schema == null) {
1272
+ continue;
1273
+ }
1274
+
1275
+ if (schema instanceof MixedSchema) {
1276
+ // allow changes to sub paths of mixed types
1277
+ mixed = true;
1278
+ break;
1279
+ }
1280
+ }
1281
+
1282
+ if (schema == null) {
1283
+ // Check for embedded discriminators
1284
+ schema = getEmbeddedDiscriminatorPath(this, path);
1285
+ }
1286
+
1287
+ if (!mixed && !schema) {
1288
+ if (strict === 'throw') {
1289
+ throw new StrictModeError(path);
1290
+ }
1291
+ return this;
1292
+ }
1293
+ } else if (pathType === 'virtual') {
1294
+ schema = this.$__schema.virtualpath(path);
1295
+ schema.applySetters(val, this);
1296
+ return this;
1297
+ } else {
1298
+ schema = this.$__path(path);
1299
+ }
1300
+
1301
+ // gh-4578, if setting a deeply nested path that doesn't exist yet, create it
1302
+ let cur = this._doc;
1303
+ let curPath = '';
1304
+ for (i = 0; i < parts.length - 1; ++i) {
1305
+ cur = cur[parts[i]];
1306
+ curPath += (curPath.length !== 0 ? '.' : '') + parts[i];
1307
+ if (!cur) {
1308
+ this.$set(curPath, {});
1309
+ // Hack re: gh-5800. If nested field is not selected, it probably exists
1310
+ // so `MongoServerError: cannot use the part (nested of nested.num) to
1311
+ // traverse the element ({nested: null})` is not likely. If user gets
1312
+ // that error, its their fault for now. We should reconsider disallowing
1313
+ // modifying not selected paths for 6.x
1314
+ if (!this.$__isSelected(curPath)) {
1315
+ this.unmarkModified(curPath);
1316
+ }
1317
+ cur = this.$__getValue(curPath);
1318
+ }
1319
+ }
1320
+
1321
+ let pathToMark;
1322
+
1323
+ // When using the $set operator the path to the field must already exist.
1324
+ // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
1325
+
1326
+ if (parts.length <= 1) {
1327
+ pathToMark = path;
1328
+ } else {
1329
+ const len = parts.length;
1330
+ for (i = 0; i < len; ++i) {
1331
+ const subpath = parts.slice(0, i + 1).join('.');
1332
+ if (this.$get(subpath, null, { getters: false }) === null) {
1333
+ pathToMark = subpath;
1334
+ break;
1335
+ }
1336
+ }
1337
+
1338
+ if (!pathToMark) {
1339
+ pathToMark = path;
1340
+ }
1341
+ }
1342
+
1343
+ if (!schema) {
1344
+ this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal);
1345
+
1346
+ if (pathType === 'nested' && val == null) {
1347
+ cleanModifiedSubpaths(this, path);
1348
+ }
1349
+ return this;
1350
+ }
1351
+
1352
+ // If overwriting a subdocument path, make sure to clear out
1353
+ // any errors _before_ setting, so new errors that happen
1354
+ // get persisted. Re: #9080
1355
+ if (schema.$isSingleNested || schema.$isMongooseArray) {
1356
+ _markValidSubpaths(this, path);
1357
+ }
1358
+
1359
+ if (val != null && merge && schema.$isSingleNested) {
1360
+ if (val instanceof Document) {
1361
+ val = val.toObject({ virtuals: false, transform: false });
1362
+ }
1363
+ const keys = Object.keys(val);
1364
+ for (const key of keys) {
1365
+ this.$set(path + '.' + key, val[key], constructing, options);
1366
+ }
1367
+
1368
+ return this;
1369
+ }
1370
+
1371
+ let shouldSet = true;
1372
+ try {
1373
+ // If the user is trying to set a ref path to a document with
1374
+ // the correct model name, treat it as populated
1375
+ const refMatches = (() => {
1376
+ if (schema.options == null) {
1377
+ return false;
1378
+ }
1379
+ if (!(val instanceof Document)) {
1380
+ return false;
1381
+ }
1382
+ const model = val.constructor;
1383
+
1384
+ // Check ref
1385
+ const ref = schema.options.ref;
1386
+ if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
1387
+ return true;
1388
+ }
1389
+
1390
+ // Check refPath
1391
+ const refPath = schema.options.refPath;
1392
+ if (refPath == null) {
1393
+ return false;
1394
+ }
1395
+ const modelName = val.get(refPath);
1396
+ return modelName === model.modelName || modelName === model.baseModelName;
1397
+ })();
1398
+
1399
+ let didPopulate = false;
1400
+ if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._id))) {
1401
+ const unpopulatedValue = (schema && schema.$isSingleNested) ? schema.cast(val, this) : val._id;
1402
+ this.$populated(path, unpopulatedValue, { [populateModelSymbol]: val.constructor });
1403
+ val.$__.wasPopulated = { value: unpopulatedValue };
1404
+ didPopulate = true;
1405
+ }
1406
+
1407
+ let popOpts;
1408
+ const typeKey = this.$__schema.options.typeKey;
1409
+ if (schema.options &&
1410
+ Array.isArray(schema.options[typeKey]) &&
1411
+ schema.options[typeKey].length &&
1412
+ schema.options[typeKey][0].ref &&
1413
+ _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) {
1414
+ popOpts = { [populateModelSymbol]: val[0].constructor };
1415
+ this.$populated(path, val.map(function(v) { return v._id; }), popOpts);
1416
+
1417
+ for (const doc of val) {
1418
+ doc.$__.wasPopulated = { value: doc._id };
1419
+ }
1420
+ didPopulate = true;
1421
+ }
1422
+
1423
+ if (this.$__schema.singleNestedPaths[path] == null && (!refMatches || !schema.$isSingleNested || !val.$__)) {
1424
+ // If this path is underneath a single nested schema, we'll call the setter
1425
+ // later in `$__set()` because we don't take `_doc` when we iterate through
1426
+ // a single nested doc. That's to make sure we get the correct context.
1427
+ // Otherwise we would double-call the setter, see gh-7196.
1428
+ if (options != null && options.overwriteImmutable) {
1429
+ val = schema.applySetters(val, this, false, priorVal, { overwriteImmutable: true });
1430
+ } else {
1431
+ val = schema.applySetters(val, this, false, priorVal);
1432
+ }
1433
+ }
1434
+
1435
+ if (Array.isArray(val) &&
1436
+ !Array.isArray(schema) &&
1437
+ schema.$isMongooseDocumentArray &&
1438
+ val.length !== 0 &&
1439
+ val[0] != null &&
1440
+ val[0].$__ != null &&
1441
+ val[0].$__.populated != null) {
1442
+ const populatedPaths = Object.keys(val[0].$__.populated);
1443
+ for (const populatedPath of populatedPaths) {
1444
+ this.$populated(path + '.' + populatedPath,
1445
+ val.map(v => v.$populated(populatedPath)),
1446
+ val[0].$__.populated[populatedPath].options);
1447
+ }
1448
+ didPopulate = true;
1449
+ }
1450
+
1451
+ if (!didPopulate && this.$__.populated) {
1452
+ // If this array partially contains populated documents, convert them
1453
+ // all to ObjectIds re: #8443
1454
+ if (Array.isArray(val) && this.$__.populated[path]) {
1455
+ for (let i = 0; i < val.length; ++i) {
1456
+ if (val[i] instanceof Document) {
1457
+ val.set(i, val[i]._id, true);
1458
+ }
1459
+ }
1460
+ }
1461
+ delete this.$__.populated[path];
1462
+ }
1463
+
1464
+ if (val != null && schema.$isSingleNested) {
1465
+ _checkImmutableSubpaths(val, schema, priorVal);
1466
+ }
1467
+
1468
+ this.$markValid(path);
1469
+ } catch (e) {
1470
+ if (e instanceof MongooseError.StrictModeError && e.isImmutableError) {
1471
+ this.invalidate(path, e);
1472
+ } else if (e instanceof MongooseError.CastError) {
1473
+ this.invalidate(e.path, e);
1474
+ if (e.$originalErrorPath) {
1475
+ this.invalidate(path,
1476
+ new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath));
1477
+ }
1478
+ } else {
1479
+ this.invalidate(path,
1480
+ new MongooseError.CastError(schema.instance, val, path, e));
1481
+ }
1482
+ shouldSet = false;
1483
+ }
1484
+
1485
+ if (shouldSet) {
1486
+ let savedState = null;
1487
+ let savedStatePath = null;
1488
+ if (!constructing) {
1489
+ const doc = this.$isSubdocument ? this.ownerDocument() : this;
1490
+ savedState = doc.$__.savedState;
1491
+ savedStatePath = this.$isSubdocument ? this.$__.fullPath + '.' + path : path;
1492
+ doc.$__saveInitialState(savedStatePath);
1493
+ }
1494
+
1495
+ this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal);
1496
+
1497
+ if (savedState != null && savedState.hasOwnProperty(savedStatePath) && utils.deepEqual(val, savedState[savedStatePath])) {
1498
+ this.unmarkModified(path);
1499
+ }
1500
+ }
1501
+
1502
+ if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
1503
+ cleanModifiedSubpaths(this, path);
1504
+ }
1505
+
1506
+ return this;
1507
+ };
1508
+
1509
+ /*!
1510
+ * ignore
1511
+ */
1512
+
1513
+ function _isManuallyPopulatedArray(val, ref) {
1514
+ if (!Array.isArray(val)) {
1515
+ return false;
1516
+ }
1517
+ if (val.length === 0) {
1518
+ return false;
1519
+ }
1520
+
1521
+ for (const el of val) {
1522
+ if (!(el instanceof Document)) {
1523
+ return false;
1524
+ }
1525
+ const modelName = el.constructor.modelName;
1526
+ if (modelName == null) {
1527
+ return false;
1528
+ }
1529
+ if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) {
1530
+ return false;
1531
+ }
1532
+ }
1533
+
1534
+ return true;
1535
+ }
1536
+
1537
+ /**
1538
+ * Sets the value of a path, or many paths.
1539
+ * Alias for [`.$set`](#document_Document-$set).
1540
+ *
1541
+ * #### Example:
1542
+ *
1543
+ * // path, value
1544
+ * doc.set(path, value)
1545
+ *
1546
+ * // object
1547
+ * doc.set({
1548
+ * path : value
1549
+ * , path2 : {
1550
+ * path : value
1551
+ * }
1552
+ * })
1553
+ *
1554
+ * // on-the-fly cast to number
1555
+ * doc.set(path, value, Number)
1556
+ *
1557
+ * // on-the-fly cast to string
1558
+ * doc.set(path, value, String)
1559
+ *
1560
+ * // changing strict mode behavior
1561
+ * doc.set(path, value, { strict: false });
1562
+ *
1563
+ * @param {String|Object} path path or object of key/vals to set
1564
+ * @param {Any} val the value to set
1565
+ * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
1566
+ * @param {Object} [options] optionally specify options that modify the behavior of the set
1567
+ * @return {Document} this
1568
+ * @api public
1569
+ * @method set
1570
+ * @memberOf Document
1571
+ * @instance
1572
+ */
1573
+
1574
+ Document.prototype.set = Document.prototype.$set;
1575
+
1576
+ /**
1577
+ * Determine if we should mark this change as modified.
1578
+ *
1579
+ * @param {never} pathToMark UNUSED
1580
+ * @param {String|Symbol} path
1581
+ * @param {Object} options
1582
+ * @param {Any} constructing
1583
+ * @param {never} parts UNUSED
1584
+ * @param {Schema} schema
1585
+ * @param {Any} val
1586
+ * @param {Any} priorVal
1587
+ * @return {Boolean}
1588
+ * @api private
1589
+ * @method $__shouldModify
1590
+ * @memberOf Document
1591
+ * @instance
1592
+ */
1593
+
1594
+ Document.prototype.$__shouldModify = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) {
1595
+ if (options && options._skipMarkModified) {
1596
+ return false;
1597
+ }
1598
+ if (this.$isNew) {
1599
+ return true;
1600
+ }
1601
+ // Is path already modified? If so, always modify. We may unmark modified later.
1602
+ if (path in this.$__.activePaths.getStatePaths('modify')) {
1603
+ return true;
1604
+ }
1605
+
1606
+ // Re: the note about gh-7196, `val` is the raw value without casting or
1607
+ // setters if the full path is under a single nested subdoc because we don't
1608
+ // want to double run setters. So don't set it as modified. See gh-7264.
1609
+ if (this.$__schema.singleNestedPaths[path] != null) {
1610
+ return false;
1611
+ }
1612
+
1613
+ if (val === void 0 && !this.$__isSelected(path)) {
1614
+ // when a path is not selected in a query, its initial
1615
+ // value will be undefined.
1616
+ return true;
1617
+ }
1618
+
1619
+ if (val === void 0 && path in this.$__.activePaths.getStatePaths('default')) {
1620
+ // we're just unsetting the default value which was never saved
1621
+ return false;
1622
+ }
1623
+
1624
+ // gh-3992: if setting a populated field to a doc, don't mark modified
1625
+ // if they have the same _id
1626
+ if (this.$populated(path) &&
1627
+ val instanceof Document &&
1628
+ deepEqual(val._id, priorVal)) {
1629
+ return false;
1630
+ }
1631
+
1632
+ if (!deepEqual(val, priorVal !== undefined ? priorVal : utils.getValue(path, this))) {
1633
+ return true;
1634
+ }
1635
+
1636
+ if (!constructing &&
1637
+ val !== null &&
1638
+ val !== undefined &&
1639
+ path in this.$__.activePaths.getStatePaths('default') &&
1640
+ deepEqual(val, schema.getDefault(this, constructing))) {
1641
+ // a path with a default was $unset on the server
1642
+ // and the user is setting it to the same value again
1643
+ return true;
1644
+ }
1645
+ return false;
1646
+ };
1647
+
1648
+ /**
1649
+ * Handles the actual setting of the value and marking the path modified if appropriate.
1650
+ *
1651
+ * @param {String} pathToMark
1652
+ * @param {String|Symbol} path
1653
+ * @param {Object} options
1654
+ * @param {Any} constructing
1655
+ * @param {Array} parts
1656
+ * @param {Schema} schema
1657
+ * @param {Any} val
1658
+ * @param {Any} priorVal
1659
+ * @api private
1660
+ * @method $__set
1661
+ * @memberOf Document
1662
+ * @instance
1663
+ */
1664
+
1665
+ Document.prototype.$__set = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) {
1666
+ Embedded = Embedded || require('./types/ArraySubdocument');
1667
+
1668
+ const shouldModify = this.$__shouldModify(pathToMark, path, options, constructing, parts,
1669
+ schema, val, priorVal);
1670
+
1671
+ if (shouldModify) {
1672
+ if (this.$__.primitiveAtomics && this.$__.primitiveAtomics[path]) {
1673
+ delete this.$__.primitiveAtomics[path];
1674
+ if (Object.keys(this.$__.primitiveAtomics).length === 0) {
1675
+ delete this.$__.primitiveAtomics;
1676
+ }
1677
+ }
1678
+ this.markModified(pathToMark);
1679
+
1680
+ // handle directly setting arrays (gh-1126)
1681
+ MongooseArray || (MongooseArray = require('./types/array'));
1682
+ if (val && utils.isMongooseArray(val)) {
1683
+ val._registerAtomic('$set', val);
1684
+
1685
+ // Update embedded document parent references (gh-5189)
1686
+ if (utils.isMongooseDocumentArray(val)) {
1687
+ val.forEach(function(item) {
1688
+ item && item.__parentArray && (item.__parentArray = val);
1689
+ });
1690
+ }
1691
+ }
1692
+ } else if (Array.isArray(val) && Array.isArray(priorVal) && utils.isMongooseArray(val) && utils.isMongooseArray(priorVal)) {
1693
+ val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol];
1694
+ val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol];
1695
+ if (utils.isMongooseDocumentArray(val)) {
1696
+ val.forEach(doc => {
1697
+ if (doc) {
1698
+ doc.isNew = false;
1699
+ }
1700
+ });
1701
+ }
1702
+ }
1703
+
1704
+ let obj = this._doc;
1705
+ let i = 0;
1706
+ const l = parts.length;
1707
+ let cur = '';
1708
+
1709
+ for (; i < l; i++) {
1710
+ const next = i + 1;
1711
+ const last = next === l;
1712
+ cur += (cur ? '.' + parts[i] : parts[i]);
1713
+ if (specialProperties.has(parts[i])) {
1714
+ return;
1715
+ }
1716
+
1717
+ if (last) {
1718
+ if (obj instanceof Map) {
1719
+ obj.set(parts[i], val);
1720
+ } else {
1721
+ obj[parts[i]] = val;
1722
+ }
1723
+ } else {
1724
+ if (utils.isPOJO(obj[parts[i]])) {
1725
+ obj = obj[parts[i]];
1726
+ } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) {
1727
+ obj = obj[parts[i]];
1728
+ } else if (obj[parts[i]] && !Array.isArray(obj[parts[i]]) && obj[parts[i]].$isSingleNested) {
1729
+ obj = obj[parts[i]];
1730
+ } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
1731
+ obj = obj[parts[i]];
1732
+ } else {
1733
+ obj[parts[i]] = obj[parts[i]] || {};
1734
+ obj = obj[parts[i]];
1735
+ }
1736
+ }
1737
+ }
1738
+ };
1739
+
1740
+ /**
1741
+ * Gets a raw value from a path (no getters)
1742
+ *
1743
+ * @param {String} path
1744
+ * @return {Any} Returns the value from the given `path`.
1745
+ * @api private
1746
+ */
1747
+
1748
+ Document.prototype.$__getValue = function(path) {
1749
+ return utils.getValue(path, this._doc);
1750
+ };
1751
+
1752
+ /**
1753
+ * Increments the numeric value at `path` by the given `val`.
1754
+ * When you call `save()` on this document, Mongoose will send a
1755
+ * [`$inc`](https://www.mongodb.com/docs/manual/reference/operator/update/inc/)
1756
+ * as opposed to a `$set`.
1757
+ *
1758
+ * #### Example:
1759
+ *
1760
+ * const schema = new Schema({ counter: Number });
1761
+ * const Test = db.model('Test', schema);
1762
+ *
1763
+ * const doc = await Test.create({ counter: 0 });
1764
+ * doc.$inc('counter', 2);
1765
+ * await doc.save(); // Sends a `{ $inc: { counter: 2 } }` to MongoDB
1766
+ * doc.counter; // 2
1767
+ *
1768
+ * doc.counter += 2;
1769
+ * await doc.save(); // Sends a `{ $set: { counter: 2 } }` to MongoDB
1770
+ *
1771
+ * @param {String|Array} path path or paths to update
1772
+ * @param {Number} val increment `path` by this value
1773
+ * @return {Document} this
1774
+ */
1775
+
1776
+ Document.prototype.$inc = function $inc(path, val) {
1777
+ if (val == null) {
1778
+ val = 1;
1779
+ }
1780
+
1781
+ if (Array.isArray(path)) {
1782
+ path.forEach((p) => this.$inc(p, val));
1783
+ return this;
1784
+ }
1785
+
1786
+ const schemaType = this.$__path(path);
1787
+ if (schemaType == null) {
1788
+ if (this.$__.strictMode === 'throw') {
1789
+ throw new StrictModeError(path);
1790
+ } else if (this.$__.strictMode === true) {
1791
+ return this;
1792
+ }
1793
+ } else if (schemaType.instance !== 'Number') {
1794
+ this.invalidate(path, new MongooseError.CastError(schemaType.instance, val, path));
1795
+ return this;
1796
+ }
1797
+
1798
+ const currentValue = this.$__getValue(path) || 0;
1799
+ let shouldSet = false;
1800
+ let valToSet = null;
1801
+ let valToInc = val;
1802
+
1803
+ try {
1804
+ val = schemaType.cast(val);
1805
+ valToSet = schemaType.applySetters(currentValue + val, this);
1806
+ valToInc = valToSet - currentValue;
1807
+ shouldSet = true;
1808
+ } catch (err) {
1809
+ this.invalidate(path, new MongooseError.CastError('number', val, path, err));
1810
+ }
1811
+
1812
+ if (shouldSet) {
1813
+ this.$__.primitiveAtomics = this.$__.primitiveAtomics || {};
1814
+ if (this.$__.primitiveAtomics[path] == null) {
1815
+ this.$__.primitiveAtomics[path] = { $inc: valToInc };
1816
+ } else {
1817
+ this.$__.primitiveAtomics[path].$inc += valToInc;
1818
+ }
1819
+ this.markModified(path);
1820
+ this.$__setValue(path, valToSet);
1821
+ }
1822
+
1823
+ return this;
1824
+ };
1825
+
1826
+ /**
1827
+ * Sets a raw value for a path (no casting, setters, transformations)
1828
+ *
1829
+ * @param {String} path
1830
+ * @param {Object} value
1831
+ * @return {Document} this
1832
+ * @api private
1833
+ */
1834
+
1835
+ Document.prototype.$__setValue = function(path, val) {
1836
+ utils.setValue(path, val, this._doc);
1837
+ return this;
1838
+ };
1839
+
1840
+ /**
1841
+ * Returns the value of a path.
1842
+ *
1843
+ * #### Example:
1844
+ *
1845
+ * // path
1846
+ * doc.get('age') // 47
1847
+ *
1848
+ * // dynamic casting to a string
1849
+ * doc.get('age', String) // "47"
1850
+ *
1851
+ * @param {String} path
1852
+ * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes
1853
+ * @param {Object} [options]
1854
+ * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path
1855
+ * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value
1856
+ * @return {Any}
1857
+ * @api public
1858
+ */
1859
+
1860
+ Document.prototype.get = function(path, type, options) {
1861
+ let adhoc;
1862
+ if (options == null) {
1863
+ options = {};
1864
+ }
1865
+ if (type) {
1866
+ adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options);
1867
+ }
1868
+ const noDottedPath = options.noDottedPath;
1869
+
1870
+ // Fast path if we know we're just accessing top-level path on the document:
1871
+ // just get the schema path, avoid `$__path()` because that does string manipulation
1872
+ let schema = noDottedPath ? this.$__schema.paths[path] : this.$__path(path);
1873
+ if (schema == null) {
1874
+ schema = this.$__schema.virtualpath(path);
1875
+
1876
+ if (schema != null) {
1877
+ return schema.applyGetters(void 0, this);
1878
+ }
1879
+ }
1880
+
1881
+ if (noDottedPath) {
1882
+ let obj = this._doc[path];
1883
+ if (adhoc) {
1884
+ obj = adhoc.cast(obj);
1885
+ }
1886
+ if (schema != null && options.getters !== false) {
1887
+ return schema.applyGetters(obj, this);
1888
+ }
1889
+ return obj;
1890
+ }
1891
+
1892
+ if (schema != null && schema.instance === 'Mixed') {
1893
+ const virtual = this.$__schema.virtualpath(path);
1894
+ if (virtual != null) {
1895
+ schema = virtual;
1896
+ }
1897
+ }
1898
+
1899
+ const hasDot = path.indexOf('.') !== -1;
1900
+ let obj = this._doc;
1901
+
1902
+ const pieces = hasDot ? path.split('.') : [path];
1903
+ // Might need to change path for top-level alias
1904
+ if (typeof this.$__schema.aliases[pieces[0]] === 'string') {
1905
+ pieces[0] = this.$__schema.aliases[pieces[0]];
1906
+ }
1907
+
1908
+ for (let i = 0, l = pieces.length; i < l; i++) {
1909
+ if (obj && obj._doc) {
1910
+ obj = obj._doc;
1911
+ }
1912
+
1913
+ if (obj == null) {
1914
+ obj = void 0;
1915
+ } else if (obj instanceof Map) {
1916
+ obj = obj.get(pieces[i], { getters: false });
1917
+ } else if (i === l - 1) {
1918
+ obj = utils.getValue(pieces[i], obj);
1919
+ } else {
1920
+ obj = obj[pieces[i]];
1921
+ }
1922
+ }
1923
+
1924
+ if (adhoc) {
1925
+ obj = adhoc.cast(obj);
1926
+ }
1927
+
1928
+ if (schema != null && options.getters !== false) {
1929
+ obj = schema.applyGetters(obj, this);
1930
+ } else if (this.$__schema.nested[path] && options.virtuals) {
1931
+ // Might need to apply virtuals if this is a nested path
1932
+ return applyVirtuals(this, utils.clone(obj) || {}, { path: path });
1933
+ }
1934
+
1935
+ return obj;
1936
+ };
1937
+
1938
+ /*!
1939
+ * ignore
1940
+ */
1941
+
1942
+ Document.prototype[getSymbol] = Document.prototype.get;
1943
+ Document.prototype.$get = Document.prototype.get;
1944
+
1945
+ /**
1946
+ * Returns the schematype for the given `path`.
1947
+ *
1948
+ * @param {String} path
1949
+ * @return {SchemaPath}
1950
+ * @api private
1951
+ * @method $__path
1952
+ * @memberOf Document
1953
+ * @instance
1954
+ */
1955
+
1956
+ Document.prototype.$__path = function(path) {
1957
+ const adhocs = this.$__.adhocPaths;
1958
+ const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null;
1959
+
1960
+ if (adhocType) {
1961
+ return adhocType;
1962
+ }
1963
+ return this.$__schema.path(path);
1964
+ };
1965
+
1966
+ /**
1967
+ * Marks the path as having pending changes to write to the db.
1968
+ *
1969
+ * _Very helpful when using [Mixed](https://mongoosejs.com/docs/schematypes.html#mixed) types._
1970
+ *
1971
+ * #### Example:
1972
+ *
1973
+ * doc.mixed.type = 'changed';
1974
+ * doc.markModified('mixed.type');
1975
+ * doc.save() // changes to mixed.type are now persisted
1976
+ *
1977
+ * @param {String} path the path to mark modified
1978
+ * @param {Document} [scope] the scope to run validators with
1979
+ * @api public
1980
+ */
1981
+
1982
+ Document.prototype.markModified = function(path, scope) {
1983
+ this.$__saveInitialState(path);
1984
+
1985
+ this.$__.activePaths.modify(path);
1986
+ if (scope != null && !this.$isSubdocument) {
1987
+ this.$__.pathsToScopes = this.$__pathsToScopes || {};
1988
+ this.$__.pathsToScopes[path] = scope;
1989
+ }
1990
+ };
1991
+
1992
+ /*!
1993
+ * ignore
1994
+ */
1995
+
1996
+ Document.prototype.$__saveInitialState = function $__saveInitialState(path) {
1997
+ const savedState = this.$__.savedState;
1998
+ const savedStatePath = path;
1999
+ if (savedState != null) {
2000
+ const firstDot = savedStatePath.indexOf('.');
2001
+ const topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot);
2002
+ if (!savedState.hasOwnProperty(topLevelPath)) {
2003
+ savedState[topLevelPath] = utils.clone(this.$__getValue(topLevelPath));
2004
+ }
2005
+ }
2006
+ };
2007
+
2008
+ /**
2009
+ * Clears the modified state on the specified path.
2010
+ *
2011
+ * #### Example:
2012
+ *
2013
+ * doc.foo = 'bar';
2014
+ * doc.unmarkModified('foo');
2015
+ * doc.save(); // changes to foo will not be persisted
2016
+ *
2017
+ * @param {String} path the path to unmark modified
2018
+ * @api public
2019
+ */
2020
+
2021
+ Document.prototype.unmarkModified = function(path) {
2022
+ this.$__.activePaths.init(path);
2023
+ if (this.$__.pathsToScopes != null) {
2024
+ delete this.$__.pathsToScopes[path];
2025
+ }
2026
+ };
2027
+
2028
+ /**
2029
+ * Don't run validation on this path or persist changes to this path.
2030
+ *
2031
+ * #### Example:
2032
+ *
2033
+ * doc.foo = null;
2034
+ * doc.$ignore('foo');
2035
+ * doc.save(); // changes to foo will not be persisted and validators won't be run
2036
+ *
2037
+ * @memberOf Document
2038
+ * @instance
2039
+ * @method $ignore
2040
+ * @param {String} path the path to ignore
2041
+ * @api public
2042
+ */
2043
+
2044
+ Document.prototype.$ignore = function(path) {
2045
+ this.$__.activePaths.ignore(path);
2046
+ };
2047
+
2048
+ /**
2049
+ * Returns the list of paths that have been directly modified. A direct
2050
+ * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
2051
+ * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
2052
+ *
2053
+ * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()`
2054
+ * because a child of `a` was directly modified.
2055
+ *
2056
+ * #### Example:
2057
+ *
2058
+ * const schema = new Schema({ foo: String, nested: { bar: String } });
2059
+ * const Model = mongoose.model('Test', schema);
2060
+ * await Model.create({ foo: 'original', nested: { bar: 'original' } });
2061
+ *
2062
+ * const doc = await Model.findOne();
2063
+ * doc.nested.bar = 'modified';
2064
+ * doc.directModifiedPaths(); // ['nested.bar']
2065
+ * doc.modifiedPaths(); // ['nested', 'nested.bar']
2066
+ *
2067
+ * @return {String[]}
2068
+ * @api public
2069
+ */
2070
+
2071
+ Document.prototype.directModifiedPaths = function() {
2072
+ return Object.keys(this.$__.activePaths.getStatePaths('modify'));
2073
+ };
2074
+
2075
+ /**
2076
+ * Returns true if the given path is nullish or only contains empty objects.
2077
+ * Useful for determining whether this subdoc will get stripped out by the
2078
+ * [minimize option](/docs/guide.html#minimize).
2079
+ *
2080
+ * #### Example:
2081
+ *
2082
+ * const schema = new Schema({ nested: { foo: String } });
2083
+ * const Model = mongoose.model('Test', schema);
2084
+ * const doc = new Model({});
2085
+ * doc.$isEmpty('nested'); // true
2086
+ * doc.nested.$isEmpty(); // true
2087
+ *
2088
+ * doc.nested.foo = 'bar';
2089
+ * doc.$isEmpty('nested'); // false
2090
+ * doc.nested.$isEmpty(); // false
2091
+ *
2092
+ * @param {String} [path]
2093
+ * @memberOf Document
2094
+ * @instance
2095
+ * @api public
2096
+ * @method $isEmpty
2097
+ * @return {Boolean}
2098
+ */
2099
+
2100
+ Document.prototype.$isEmpty = function(path) {
2101
+ const isEmptyOptions = {
2102
+ minimize: true,
2103
+ virtuals: false,
2104
+ getters: false,
2105
+ transform: false
2106
+ };
2107
+
2108
+ if (arguments.length !== 0) {
2109
+ const v = this.$get(path);
2110
+ if (v == null) {
2111
+ return true;
2112
+ }
2113
+ if (typeof v !== 'object') {
2114
+ return false;
2115
+ }
2116
+ if (utils.isPOJO(v)) {
2117
+ return _isEmpty(v);
2118
+ }
2119
+ return Object.keys(v.toObject(isEmptyOptions)).length === 0;
2120
+ }
2121
+
2122
+ return Object.keys(this.toObject(isEmptyOptions)).length === 0;
2123
+ };
2124
+
2125
+ /*!
2126
+ * ignore
2127
+ */
2128
+
2129
+ function _isEmpty(v) {
2130
+ if (v == null) {
2131
+ return true;
2132
+ }
2133
+ if (typeof v !== 'object' || Array.isArray(v)) {
2134
+ return false;
2135
+ }
2136
+ for (const key of Object.keys(v)) {
2137
+ if (!_isEmpty(v[key])) {
2138
+ return false;
2139
+ }
2140
+ }
2141
+ return true;
2142
+ }
2143
+
2144
+ /**
2145
+ * Returns the list of paths that have been modified.
2146
+ *
2147
+ * @param {Object} [options]
2148
+ * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`.
2149
+ * @return {String[]}
2150
+ * @api public
2151
+ */
2152
+
2153
+ Document.prototype.modifiedPaths = function(options) {
2154
+ options = options || {};
2155
+
2156
+ const directModifiedPaths = Object.keys(this.$__.activePaths.getStatePaths('modify'));
2157
+ const result = new Set();
2158
+
2159
+ let i = 0;
2160
+ let j = 0;
2161
+ const len = directModifiedPaths.length;
2162
+
2163
+ for (i = 0; i < len; ++i) {
2164
+ const path = directModifiedPaths[i];
2165
+ const parts = parentPaths(path);
2166
+ const pLen = parts.length;
2167
+
2168
+ for (j = 0; j < pLen; ++j) {
2169
+ result.add(parts[j]);
2170
+ }
2171
+
2172
+ if (!options.includeChildren) {
2173
+ continue;
2174
+ }
2175
+
2176
+ let ii = 0;
2177
+ let cur = this.$get(path);
2178
+ if (typeof cur === 'object' && cur !== null) {
2179
+ if (cur._doc) {
2180
+ cur = cur._doc;
2181
+ }
2182
+ const len = cur.length;
2183
+ if (Array.isArray(cur)) {
2184
+ for (ii = 0; ii < len; ++ii) {
2185
+ const subPath = path + '.' + ii;
2186
+ if (!result.has(subPath)) {
2187
+ result.add(subPath);
2188
+ if (cur[ii] != null && cur[ii].$__) {
2189
+ const modified = cur[ii].modifiedPaths();
2190
+ let iii = 0;
2191
+ const iiiLen = modified.length;
2192
+ for (iii = 0; iii < iiiLen; ++iii) {
2193
+ result.add(subPath + '.' + modified[iii]);
2194
+ }
2195
+ }
2196
+ }
2197
+ }
2198
+ } else {
2199
+ const keys = Object.keys(cur);
2200
+ let ii = 0;
2201
+ const len = keys.length;
2202
+ for (ii = 0; ii < len; ++ii) {
2203
+ result.add(path + '.' + keys[ii]);
2204
+ }
2205
+ }
2206
+ }
2207
+ }
2208
+ return Array.from(result);
2209
+ };
2210
+
2211
+ Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths;
2212
+
2213
+ /**
2214
+ * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path
2215
+ * in this document is modified.
2216
+ *
2217
+ * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.
2218
+ *
2219
+ * #### Example:
2220
+ *
2221
+ * doc.set('documents.0.title', 'changed');
2222
+ * doc.isModified() // true
2223
+ * doc.isModified('documents') // true
2224
+ * doc.isModified('documents.0.title') // true
2225
+ * doc.isModified('documents otherProp') // true
2226
+ * doc.isDirectModified('documents') // false
2227
+ *
2228
+ * @param {String} [path] optional
2229
+ * @param {Object} [options]
2230
+ * @param {Boolean} [options.ignoreAtomics=false] If true, doesn't return true if path is underneath an array that was modified with atomic operations like `push()`
2231
+ * @return {Boolean}
2232
+ * @api public
2233
+ */
2234
+
2235
+ Document.prototype.isModified = function(paths, options, modifiedPaths) {
2236
+ if (paths) {
2237
+ const ignoreAtomics = options && options.ignoreAtomics;
2238
+ const directModifiedPathsObj = this.$__.activePaths.states.modify;
2239
+ if (directModifiedPathsObj == null) {
2240
+ return false;
2241
+ }
2242
+
2243
+ if (typeof paths === 'string') {
2244
+ paths = paths.indexOf(' ') === -1 ? [paths] : paths.split(' ');
2245
+ }
2246
+
2247
+ for (const path of paths) {
2248
+ if (directModifiedPathsObj[path] != null) {
2249
+ return true;
2250
+ }
2251
+ }
2252
+
2253
+ const modified = modifiedPaths || this[documentModifiedPaths]();
2254
+ const isModifiedChild = paths.some(function(path) {
2255
+ return !!~modified.indexOf(path);
2256
+ });
2257
+
2258
+ let directModifiedPaths = Object.keys(directModifiedPathsObj);
2259
+ if (ignoreAtomics) {
2260
+ directModifiedPaths = directModifiedPaths.filter(path => {
2261
+ const value = this.$__getValue(path);
2262
+ if (value != null && value[arrayAtomicsSymbol] != null && value[arrayAtomicsSymbol].$set === undefined) {
2263
+ return false;
2264
+ }
2265
+ return true;
2266
+ });
2267
+ }
2268
+ return isModifiedChild || paths.some(function(path) {
2269
+ return directModifiedPaths.some(function(mod) {
2270
+ return mod === path || path.startsWith(mod + '.');
2271
+ });
2272
+ });
2273
+ }
2274
+
2275
+ return this.$__.activePaths.some('modify');
2276
+ };
2277
+
2278
+ /**
2279
+ * Alias of [`.isModified`](#document_Document-isModified)
2280
+ *
2281
+ * @method $isModified
2282
+ * @memberOf Document
2283
+ * @api public
2284
+ */
2285
+
2286
+ Document.prototype.$isModified = Document.prototype.isModified;
2287
+
2288
+ Document.prototype[documentIsModified] = Document.prototype.isModified;
2289
+
2290
+ /**
2291
+ * Checks if a path is set to its default.
2292
+ *
2293
+ * #### Example:
2294
+ *
2295
+ * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
2296
+ * const m = new MyModel();
2297
+ * m.$isDefault('name'); // true
2298
+ *
2299
+ * @memberOf Document
2300
+ * @instance
2301
+ * @method $isDefault
2302
+ * @param {String} [path]
2303
+ * @return {Boolean}
2304
+ * @api public
2305
+ */
2306
+
2307
+ Document.prototype.$isDefault = function(path) {
2308
+ if (path == null) {
2309
+ return this.$__.activePaths.some('default');
2310
+ }
2311
+
2312
+ if (typeof path === 'string' && path.indexOf(' ') === -1) {
2313
+ return this.$__.activePaths.getStatePaths('default').hasOwnProperty(path);
2314
+ }
2315
+
2316
+ let paths = path;
2317
+ if (!Array.isArray(paths)) {
2318
+ paths = paths.split(' ');
2319
+ }
2320
+
2321
+ return paths.some(path => this.$__.activePaths.getStatePaths('default').hasOwnProperty(path));
2322
+ };
2323
+
2324
+ /**
2325
+ * Getter/setter, determines whether the document was removed or not.
2326
+ *
2327
+ * #### Example:
2328
+ *
2329
+ * const product = await product.remove();
2330
+ * product.$isDeleted(); // true
2331
+ * product.remove(); // no-op, doesn't send anything to the db
2332
+ *
2333
+ * product.$isDeleted(false);
2334
+ * product.$isDeleted(); // false
2335
+ * product.remove(); // will execute a remove against the db
2336
+ *
2337
+ *
2338
+ * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted
2339
+ * @return {Boolean|Document} whether mongoose thinks this doc is deleted.
2340
+ * @method $isDeleted
2341
+ * @memberOf Document
2342
+ * @instance
2343
+ * @api public
2344
+ */
2345
+
2346
+ Document.prototype.$isDeleted = function(val) {
2347
+ if (arguments.length === 0) {
2348
+ return !!this.$__.isDeleted;
2349
+ }
2350
+
2351
+ this.$__.isDeleted = !!val;
2352
+ return this;
2353
+ };
2354
+
2355
+ /**
2356
+ * Returns true if `path` was directly set and modified, else false.
2357
+ *
2358
+ * #### Example:
2359
+ *
2360
+ * doc.set('documents.0.title', 'changed');
2361
+ * doc.isDirectModified('documents.0.title') // true
2362
+ * doc.isDirectModified('documents') // false
2363
+ *
2364
+ * @param {String|String[]} [path]
2365
+ * @return {Boolean}
2366
+ * @api public
2367
+ */
2368
+
2369
+ Document.prototype.isDirectModified = function(path) {
2370
+ if (path == null) {
2371
+ return this.$__.activePaths.some('modify');
2372
+ }
2373
+
2374
+ if (typeof path === 'string' && path.indexOf(' ') === -1) {
2375
+ return this.$__.activePaths.getStatePaths('modify').hasOwnProperty(path);
2376
+ }
2377
+
2378
+ let paths = path;
2379
+ if (!Array.isArray(paths)) {
2380
+ paths = paths.split(' ');
2381
+ }
2382
+
2383
+ return paths.some(path => this.$__.activePaths.getStatePaths('modify').hasOwnProperty(path));
2384
+ };
2385
+
2386
+ /**
2387
+ * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since.
2388
+ *
2389
+ * @param {String} [path]
2390
+ * @return {Boolean}
2391
+ * @api public
2392
+ */
2393
+
2394
+ Document.prototype.isInit = function(path) {
2395
+ if (path == null) {
2396
+ return this.$__.activePaths.some('init');
2397
+ }
2398
+
2399
+ if (typeof path === 'string' && path.indexOf(' ') === -1) {
2400
+ return this.$__.activePaths.getStatePaths('init').hasOwnProperty(path);
2401
+ }
2402
+
2403
+ let paths = path;
2404
+ if (!Array.isArray(paths)) {
2405
+ paths = paths.split(' ');
2406
+ }
2407
+
2408
+ return paths.some(path => this.$__.activePaths.getStatePaths('init').hasOwnProperty(path));
2409
+ };
2410
+
2411
+ /**
2412
+ * Checks if `path` was selected in the source query which initialized this document.
2413
+ *
2414
+ * #### Example:
2415
+ *
2416
+ * const doc = await Thing.findOne().select('name');
2417
+ * doc.isSelected('name') // true
2418
+ * doc.isSelected('age') // false
2419
+ *
2420
+ * @param {String|String[]} path
2421
+ * @return {Boolean}
2422
+ * @api public
2423
+ */
2424
+
2425
+ Document.prototype.isSelected = function isSelected(path) {
2426
+ if (this.$__.selected == null) {
2427
+ return true;
2428
+ }
2429
+ if (!path) {
2430
+ return false;
2431
+ }
2432
+ if (path === '_id') {
2433
+ return this.$__.selected._id !== 0;
2434
+ }
2435
+
2436
+ if (path.indexOf(' ') !== -1) {
2437
+ path = path.split(' ');
2438
+ }
2439
+ if (Array.isArray(path)) {
2440
+ return path.some(p => this.$__isSelected(p));
2441
+ }
2442
+
2443
+ const paths = Object.keys(this.$__.selected);
2444
+ let inclusive = null;
2445
+
2446
+ if (paths.length === 1 && paths[0] === '_id') {
2447
+ // only _id was selected.
2448
+ return this.$__.selected._id === 0;
2449
+ }
2450
+
2451
+ for (const cur of paths) {
2452
+ if (cur === '_id') {
2453
+ continue;
2454
+ }
2455
+ if (!isDefiningProjection(this.$__.selected[cur])) {
2456
+ continue;
2457
+ }
2458
+ inclusive = !!this.$__.selected[cur];
2459
+ break;
2460
+ }
2461
+
2462
+ if (inclusive === null) {
2463
+ return true;
2464
+ }
2465
+
2466
+ if (path in this.$__.selected) {
2467
+ return inclusive;
2468
+ }
2469
+
2470
+ const pathDot = path + '.';
2471
+
2472
+ for (const cur of paths) {
2473
+ if (cur === '_id') {
2474
+ continue;
2475
+ }
2476
+
2477
+ if (cur.startsWith(pathDot)) {
2478
+ return inclusive || cur !== pathDot;
2479
+ }
2480
+
2481
+ if (pathDot.startsWith(cur + '.')) {
2482
+ return inclusive;
2483
+ }
2484
+ }
2485
+
2486
+ return !inclusive;
2487
+ };
2488
+
2489
+ Document.prototype.$__isSelected = Document.prototype.isSelected;
2490
+
2491
+ /**
2492
+ * Checks if `path` was explicitly selected. If no projection, always returns
2493
+ * true.
2494
+ *
2495
+ * #### Example:
2496
+ *
2497
+ * Thing.findOne().select('nested.name').exec(function (err, doc) {
2498
+ * doc.isDirectSelected('nested.name') // true
2499
+ * doc.isDirectSelected('nested.otherName') // false
2500
+ * doc.isDirectSelected('nested') // false
2501
+ * })
2502
+ *
2503
+ * @param {String} path
2504
+ * @return {Boolean}
2505
+ * @api public
2506
+ */
2507
+
2508
+ Document.prototype.isDirectSelected = function isDirectSelected(path) {
2509
+ if (this.$__.selected == null) {
2510
+ return true;
2511
+ }
2512
+
2513
+ if (path === '_id') {
2514
+ return this.$__.selected._id !== 0;
2515
+ }
2516
+
2517
+ if (path.indexOf(' ') !== -1) {
2518
+ path = path.split(' ');
2519
+ }
2520
+ if (Array.isArray(path)) {
2521
+ return path.some(p => this.isDirectSelected(p));
2522
+ }
2523
+
2524
+ const paths = Object.keys(this.$__.selected);
2525
+ let inclusive = null;
2526
+
2527
+ if (paths.length === 1 && paths[0] === '_id') {
2528
+ // only _id was selected.
2529
+ return this.$__.selected._id === 0;
2530
+ }
2531
+
2532
+ for (const cur of paths) {
2533
+ if (cur === '_id') {
2534
+ continue;
2535
+ }
2536
+ if (!isDefiningProjection(this.$__.selected[cur])) {
2537
+ continue;
2538
+ }
2539
+ inclusive = !!this.$__.selected[cur];
2540
+ break;
2541
+ }
2542
+
2543
+ if (inclusive === null) {
2544
+ return true;
2545
+ }
2546
+
2547
+ if (this.$__.selected.hasOwnProperty(path)) {
2548
+ return inclusive;
2549
+ }
2550
+
2551
+ return !inclusive;
2552
+ };
2553
+
2554
+ /**
2555
+ * Executes registered validation rules for this document.
2556
+ *
2557
+ * #### Note:
2558
+ *
2559
+ * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`.
2560
+ *
2561
+ * #### Example:
2562
+ *
2563
+ * doc.validate(function (err) {
2564
+ * if (err) handleError(err);
2565
+ * else // validation passed
2566
+ * });
2567
+ *
2568
+ * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.
2569
+ * @param {Object} [options] internal options
2570
+ * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths.
2571
+ * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.
2572
+ * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred
2573
+ * @return {Promise} Returns a Promise if no `callback` is given.
2574
+ * @api public
2575
+ */
2576
+
2577
+ Document.prototype.validate = function(pathsToValidate, options, callback) {
2578
+ let parallelValidate;
2579
+ this.$op = 'validate';
2580
+
2581
+ if (this.$isSubdocument != null) {
2582
+ // Skip parallel validate check for subdocuments
2583
+ } else if (this.$__.validating) {
2584
+ parallelValidate = new ParallelValidateError(this, {
2585
+ parentStack: options && options.parentStack,
2586
+ conflictStack: this.$__.validating.stack
2587
+ });
2588
+ } else {
2589
+ this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack });
2590
+ }
2591
+
2592
+ if (arguments.length === 1) {
2593
+ if (typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) {
2594
+ options = arguments[0];
2595
+ callback = null;
2596
+ pathsToValidate = null;
2597
+ } else if (typeof arguments[0] === 'function') {
2598
+ callback = arguments[0];
2599
+ options = null;
2600
+ pathsToValidate = null;
2601
+ }
2602
+ } else if (typeof pathsToValidate === 'function') {
2603
+ callback = pathsToValidate;
2604
+ options = null;
2605
+ pathsToValidate = null;
2606
+ } else if (typeof options === 'function') {
2607
+ callback = options;
2608
+ options = pathsToValidate;
2609
+ pathsToValidate = null;
2610
+ }
2611
+ if (options && typeof options.pathsToSkip === 'string') {
2612
+ const isOnePathOnly = options.pathsToSkip.indexOf(' ') === -1;
2613
+ options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(' ');
2614
+ }
2615
+
2616
+ return promiseOrCallback(callback, cb => {
2617
+ if (parallelValidate != null) {
2618
+ return cb(parallelValidate);
2619
+ }
2620
+
2621
+ this.$__validate(pathsToValidate, options, (error) => {
2622
+ this.$op = null;
2623
+ this.$__.validating = null;
2624
+ cb(error);
2625
+ });
2626
+ }, this.constructor.events);
2627
+ };
2628
+
2629
+ /**
2630
+ * Alias of [`.validate`](#document_Document-validate)
2631
+ *
2632
+ * @method $validate
2633
+ * @memberOf Document
2634
+ * @api public
2635
+ */
2636
+
2637
+ Document.prototype.$validate = Document.prototype.validate;
2638
+
2639
+ /*!
2640
+ * ignore
2641
+ */
2642
+
2643
+ function _evaluateRequiredFunctions(doc) {
2644
+ const requiredFields = Object.keys(doc.$__.activePaths.getStatePaths('require'));
2645
+ let i = 0;
2646
+ const len = requiredFields.length;
2647
+ for (i = 0; i < len; ++i) {
2648
+ const path = requiredFields[i];
2649
+
2650
+ const p = doc.$__schema.path(path);
2651
+
2652
+ if (p != null && typeof p.originalRequiredValue === 'function') {
2653
+ doc.$__.cachedRequired = doc.$__.cachedRequired || {};
2654
+ try {
2655
+ doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc);
2656
+ } catch (err) {
2657
+ doc.invalidate(path, err);
2658
+ }
2659
+ }
2660
+ }
2661
+ }
2662
+
2663
+ /*!
2664
+ * ignore
2665
+ */
2666
+
2667
+ function _getPathsToValidate(doc) {
2668
+ const doValidateOptions = {};
2669
+
2670
+ _evaluateRequiredFunctions(doc);
2671
+ // only validate required fields when necessary
2672
+ let paths = new Set(Object.keys(doc.$__.activePaths.getStatePaths('require')).filter(function(path) {
2673
+ if (!doc.$__isSelected(path) && !doc.$isModified(path)) {
2674
+ return false;
2675
+ }
2676
+ if (doc.$__.cachedRequired != null && path in doc.$__.cachedRequired) {
2677
+ return doc.$__.cachedRequired[path];
2678
+ }
2679
+ return true;
2680
+ }));
2681
+
2682
+ Object.keys(doc.$__.activePaths.getStatePaths('init')).forEach(addToPaths);
2683
+ Object.keys(doc.$__.activePaths.getStatePaths('modify')).forEach(addToPaths);
2684
+ Object.keys(doc.$__.activePaths.getStatePaths('default')).forEach(addToPaths);
2685
+ function addToPaths(p) { paths.add(p); }
2686
+
2687
+ const subdocs = doc.$getAllSubdocs();
2688
+ const modifiedPaths = doc.modifiedPaths();
2689
+ for (const subdoc of subdocs) {
2690
+ if (subdoc.$basePath) {
2691
+ const fullPathToSubdoc = subdoc.$__fullPathWithIndexes();
2692
+
2693
+ // Remove child paths for now, because we'll be validating the whole
2694
+ // subdoc.
2695
+ // The following is a faster take on looping through every path in `paths`
2696
+ // and checking if the path starts with `fullPathToSubdoc` re: gh-13191
2697
+ for (const modifiedPath of subdoc.modifiedPaths()) {
2698
+ paths.delete(fullPathToSubdoc + '.' + modifiedPath);
2699
+ }
2700
+
2701
+ if (doc.$isModified(fullPathToSubdoc, null, modifiedPaths) &&
2702
+ !doc.isDirectModified(fullPathToSubdoc) &&
2703
+ !doc.$isDefault(fullPathToSubdoc)) {
2704
+ paths.add(fullPathToSubdoc);
2705
+ if (doc.$__.pathsToScopes == null) {
2706
+ doc.$__.pathsToScopes = {};
2707
+ }
2708
+ doc.$__.pathsToScopes[fullPathToSubdoc] = subdoc.$isDocumentArrayElement ?
2709
+ subdoc.__parentArray :
2710
+ subdoc.$parent();
2711
+
2712
+ doValidateOptions[fullPathToSubdoc] = { skipSchemaValidators: true };
2713
+ if (subdoc.$isDocumentArrayElement && subdoc.__index != null) {
2714
+ doValidateOptions[fullPathToSubdoc].index = subdoc.__index;
2715
+ }
2716
+ }
2717
+ }
2718
+ }
2719
+
2720
+ for (const path of paths) {
2721
+ const _pathType = doc.$__schema.path(path);
2722
+ if (!_pathType) {
2723
+ continue;
2724
+ }
2725
+
2726
+ if (_pathType.$isMongooseDocumentArray) {
2727
+ for (const p of paths) {
2728
+ if (p == null || p.startsWith(_pathType.path + '.')) {
2729
+ paths.delete(p);
2730
+ }
2731
+ }
2732
+ }
2733
+
2734
+ // Optimization: if primitive path with no validators, or array of primitives
2735
+ // with no validators, skip validating this path entirely.
2736
+ if (!_pathType.caster && _pathType.validators.length === 0) {
2737
+ paths.delete(path);
2738
+ } else if (_pathType.$isMongooseArray &&
2739
+ !_pathType.$isMongooseDocumentArray && // Skip document arrays...
2740
+ !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays
2741
+ _pathType.validators.length === 0 && // and arrays with top-level validators
2742
+ _pathType.$embeddedSchemaType.validators.length === 0) {
2743
+ paths.delete(path);
2744
+ }
2745
+ }
2746
+
2747
+ // from here on we're not removing items from paths
2748
+
2749
+ // gh-661: if a whole array is modified, make sure to run validation on all
2750
+ // the children as well
2751
+ for (const path of paths) {
2752
+ const _pathType = doc.$__schema.path(path);
2753
+ if (!_pathType) {
2754
+ continue;
2755
+ }
2756
+
2757
+ if (!_pathType.$isMongooseArray ||
2758
+ // To avoid potential performance issues, skip doc arrays whose children
2759
+ // are not required. `getPositionalPathType()` may be slow, so avoid
2760
+ // it unless we have a case of #6364
2761
+ (!Array.isArray(_pathType) &&
2762
+ _pathType.$isMongooseDocumentArray &&
2763
+ !(_pathType && _pathType.schemaOptions && _pathType.schemaOptions.required))) {
2764
+ continue;
2765
+ }
2766
+
2767
+ // gh-11380: optimization. If the array isn't a document array and there's no validators
2768
+ // on the array type, there's no need to run validation on the individual array elements.
2769
+ if (_pathType.$isMongooseArray &&
2770
+ !_pathType.$isMongooseDocumentArray && // Skip document arrays...
2771
+ !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays
2772
+ _pathType.$embeddedSchemaType.validators.length === 0) {
2773
+ continue;
2774
+ }
2775
+
2776
+ const val = doc.$__getValue(path);
2777
+ _pushNestedArrayPaths(val, paths, path);
2778
+ }
2779
+
2780
+ function _pushNestedArrayPaths(val, paths, path) {
2781
+ if (val != null) {
2782
+ const numElements = val.length;
2783
+ for (let j = 0; j < numElements; ++j) {
2784
+ if (Array.isArray(val[j])) {
2785
+ _pushNestedArrayPaths(val[j], paths, path + '.' + j);
2786
+ } else {
2787
+ paths.add(path + '.' + j);
2788
+ }
2789
+ }
2790
+ }
2791
+ }
2792
+
2793
+ const flattenOptions = { skipArrays: true };
2794
+ for (const pathToCheck of paths) {
2795
+ if (doc.$__schema.nested[pathToCheck]) {
2796
+ let _v = doc.$__getValue(pathToCheck);
2797
+ if (isMongooseObject(_v)) {
2798
+ _v = _v.toObject({ transform: false });
2799
+ }
2800
+ const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema);
2801
+ Object.keys(flat).forEach(addToPaths);
2802
+ }
2803
+ }
2804
+
2805
+ for (const path of paths) {
2806
+ // Single nested paths (paths embedded under single nested subdocs) will
2807
+ // be validated on their own when we call `validate()` on the subdoc itself.
2808
+ // Re: gh-8468
2809
+ if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) {
2810
+ paths.delete(path);
2811
+ continue;
2812
+ }
2813
+ const _pathType = doc.$__schema.path(path);
2814
+ if (!_pathType || !_pathType.$isSchemaMap) {
2815
+ continue;
2816
+ }
2817
+
2818
+ const val = doc.$__getValue(path);
2819
+ if (val == null) {
2820
+ continue;
2821
+ }
2822
+ for (const key of val.keys()) {
2823
+ paths.add(path + '.' + key);
2824
+ }
2825
+ }
2826
+
2827
+ paths = Array.from(paths);
2828
+ return [paths, doValidateOptions];
2829
+ }
2830
+
2831
+ /*!
2832
+ * ignore
2833
+ */
2834
+
2835
+ Document.prototype.$__validate = function(pathsToValidate, options, callback) {
2836
+ if (typeof pathsToValidate === 'function') {
2837
+ callback = pathsToValidate;
2838
+ options = null;
2839
+ pathsToValidate = null;
2840
+ } else if (typeof options === 'function') {
2841
+ callback = options;
2842
+ options = null;
2843
+ }
2844
+
2845
+ const hasValidateModifiedOnlyOption = options &&
2846
+ (typeof options === 'object') &&
2847
+ ('validateModifiedOnly' in options);
2848
+
2849
+ const pathsToSkip = (options && options.pathsToSkip) || null;
2850
+
2851
+ let shouldValidateModifiedOnly;
2852
+ if (hasValidateModifiedOnlyOption) {
2853
+ shouldValidateModifiedOnly = !!options.validateModifiedOnly;
2854
+ } else {
2855
+ shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly;
2856
+ }
2857
+
2858
+ const _this = this;
2859
+ const _complete = () => {
2860
+ let validationError = this.$__.validationError;
2861
+ this.$__.validationError = null;
2862
+ this.$__.validating = null;
2863
+
2864
+ if (shouldValidateModifiedOnly && validationError != null) {
2865
+ // Remove any validation errors that aren't from modified paths
2866
+ const errors = Object.keys(validationError.errors);
2867
+ for (const errPath of errors) {
2868
+ if (!this.$isModified(errPath)) {
2869
+ delete validationError.errors[errPath];
2870
+ }
2871
+ }
2872
+ if (Object.keys(validationError.errors).length === 0) {
2873
+ validationError = void 0;
2874
+ }
2875
+ }
2876
+
2877
+ this.$__.cachedRequired = {};
2878
+ this.$emit('validate', _this);
2879
+ this.constructor.emit('validate', _this);
2880
+
2881
+ if (validationError) {
2882
+ for (const key in validationError.errors) {
2883
+ // Make sure cast errors persist
2884
+ if (!this[documentArrayParent] &&
2885
+ validationError.errors[key] instanceof MongooseError.CastError) {
2886
+ this.invalidate(key, validationError.errors[key]);
2887
+ }
2888
+ }
2889
+
2890
+ return validationError;
2891
+ }
2892
+ };
2893
+
2894
+ // only validate required fields when necessary
2895
+ const pathDetails = _getPathsToValidate(this);
2896
+ let paths = shouldValidateModifiedOnly ?
2897
+ pathDetails[0].filter((path) => this.$isModified(path)) :
2898
+ pathDetails[0];
2899
+ const doValidateOptionsByPath = pathDetails[1];
2900
+ if (typeof pathsToValidate === 'string') {
2901
+ pathsToValidate = pathsToValidate.split(' ');
2902
+ }
2903
+ if (Array.isArray(pathsToValidate)) {
2904
+ paths = _handlePathsToValidate(paths, pathsToValidate);
2905
+ } else if (pathsToSkip) {
2906
+ paths = _handlePathsToSkip(paths, pathsToSkip);
2907
+ }
2908
+
2909
+ if (paths.length === 0) {
2910
+ return immediate(function() {
2911
+ const error = _complete();
2912
+ if (error) {
2913
+ return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
2914
+ callback(error);
2915
+ });
2916
+ }
2917
+ callback(null, _this);
2918
+ });
2919
+ }
2920
+
2921
+ const validated = {};
2922
+ let total = 0;
2923
+
2924
+ for (const path of paths) {
2925
+ validatePath(path);
2926
+ }
2927
+
2928
+ function validatePath(path) {
2929
+ if (path == null || validated[path]) {
2930
+ return;
2931
+ }
2932
+
2933
+ validated[path] = true;
2934
+ total++;
2935
+
2936
+ immediate(function() {
2937
+ const schemaType = _this.$__schema.path(path);
2938
+
2939
+ if (!schemaType) {
2940
+ return --total || complete();
2941
+ }
2942
+
2943
+ // If user marked as invalid or there was a cast error, don't validate
2944
+ if (!_this.$isValid(path)) {
2945
+ --total || complete();
2946
+ return;
2947
+ }
2948
+
2949
+ // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141)
2950
+ if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) {
2951
+ return --total || complete();
2952
+ }
2953
+
2954
+ let val = _this.$__getValue(path);
2955
+
2956
+ // If you `populate()` and get back a null value, required validators
2957
+ // shouldn't fail (gh-8018). We should always fall back to the populated
2958
+ // value.
2959
+ let pop;
2960
+ if ((pop = _this.$populated(path))) {
2961
+ val = pop;
2962
+ } else if (val != null && val.$__ != null && val.$__.wasPopulated) {
2963
+ // Array paths, like `somearray.1`, do not show up as populated with `$populated()`,
2964
+ // so in that case pull out the document's id
2965
+ val = val._id;
2966
+ }
2967
+ const scope = _this.$__.pathsToScopes != null && path in _this.$__.pathsToScopes ?
2968
+ _this.$__.pathsToScopes[path] :
2969
+ _this;
2970
+
2971
+ const doValidateOptions = {
2972
+ ...doValidateOptionsByPath[path],
2973
+ path: path,
2974
+ validateModifiedOnly: shouldValidateModifiedOnly
2975
+ };
2976
+
2977
+ schemaType.doValidate(val, function(err) {
2978
+ if (err) {
2979
+ const isSubdoc = schemaType.$isSingleNested ||
2980
+ schemaType.$isArraySubdocument ||
2981
+ schemaType.$isMongooseDocumentArray;
2982
+ if (isSubdoc && err instanceof ValidationError) {
2983
+ return --total || complete();
2984
+ }
2985
+ _this.invalidate(path, err, undefined, true);
2986
+ }
2987
+ --total || complete();
2988
+ }, scope, doValidateOptions);
2989
+ });
2990
+ }
2991
+
2992
+ function complete() {
2993
+ const error = _complete();
2994
+ if (error) {
2995
+ return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
2996
+ callback(error);
2997
+ });
2998
+ }
2999
+ callback(null, _this);
3000
+ }
3001
+
3002
+ };
3003
+
3004
+ /*!
3005
+ * ignore
3006
+ */
3007
+
3008
+ function _handlePathsToValidate(paths, pathsToValidate) {
3009
+ const _pathsToValidate = new Set(pathsToValidate);
3010
+ const parentPaths = new Map([]);
3011
+ for (const path of pathsToValidate) {
3012
+ if (path.indexOf('.') === -1) {
3013
+ continue;
3014
+ }
3015
+ const pieces = path.split('.');
3016
+ let cur = pieces[0];
3017
+ for (let i = 1; i < pieces.length; ++i) {
3018
+ // Since we skip subpaths under single nested subdocs to
3019
+ // avoid double validation, we need to add back the
3020
+ // single nested subpath if the user asked for it (gh-8626)
3021
+ parentPaths.set(cur, path);
3022
+ cur = cur + '.' + pieces[i];
3023
+ }
3024
+ }
3025
+
3026
+ const ret = [];
3027
+ for (const path of paths) {
3028
+ if (_pathsToValidate.has(path)) {
3029
+ ret.push(path);
3030
+ } else if (parentPaths.has(path)) {
3031
+ ret.push(parentPaths.get(path));
3032
+ }
3033
+ }
3034
+ return ret;
3035
+ }
3036
+
3037
+ /*!
3038
+ * ignore
3039
+ */
3040
+
3041
+ function _handlePathsToSkip(paths, pathsToSkip) {
3042
+ pathsToSkip = new Set(pathsToSkip);
3043
+ paths = paths.filter(p => !pathsToSkip.has(p));
3044
+ return paths;
3045
+ }
3046
+
3047
+ /**
3048
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
3049
+ *
3050
+ * #### Note:
3051
+ *
3052
+ * This method is useful if you need synchronous validation.
3053
+ *
3054
+ * #### Example:
3055
+ *
3056
+ * const err = doc.validateSync();
3057
+ * if (err) {
3058
+ * handleError(err);
3059
+ * } else {
3060
+ * // validation passed
3061
+ * }
3062
+ *
3063
+ * @param {Array|string} [pathsToValidate] only validate the given paths
3064
+ * @param {Object} [options] options for validation
3065
+ * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
3066
+ * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.
3067
+ * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error.
3068
+ * @api public
3069
+ */
3070
+
3071
+ Document.prototype.validateSync = function(pathsToValidate, options) {
3072
+ const _this = this;
3073
+
3074
+ if (arguments.length === 1 && typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) {
3075
+ options = arguments[0];
3076
+ pathsToValidate = null;
3077
+ }
3078
+
3079
+ const hasValidateModifiedOnlyOption = options &&
3080
+ (typeof options === 'object') &&
3081
+ ('validateModifiedOnly' in options);
3082
+
3083
+ let shouldValidateModifiedOnly;
3084
+ if (hasValidateModifiedOnlyOption) {
3085
+ shouldValidateModifiedOnly = !!options.validateModifiedOnly;
3086
+ } else {
3087
+ shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly;
3088
+ }
3089
+
3090
+ let pathsToSkip = options && options.pathsToSkip;
3091
+
3092
+ if (typeof pathsToValidate === 'string') {
3093
+ const isOnePathOnly = pathsToValidate.indexOf(' ') === -1;
3094
+ pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(' ');
3095
+ } else if (typeof pathsToSkip === 'string' && pathsToSkip.indexOf(' ') !== -1) {
3096
+ pathsToSkip = pathsToSkip.split(' ');
3097
+ }
3098
+
3099
+ // only validate required fields when necessary
3100
+ const pathDetails = _getPathsToValidate(this);
3101
+ let paths = shouldValidateModifiedOnly ?
3102
+ pathDetails[0].filter((path) => this.$isModified(path)) :
3103
+ pathDetails[0];
3104
+ const skipSchemaValidators = pathDetails[1];
3105
+
3106
+ if (Array.isArray(pathsToValidate)) {
3107
+ paths = _handlePathsToValidate(paths, pathsToValidate);
3108
+ } else if (Array.isArray(pathsToSkip)) {
3109
+ paths = _handlePathsToSkip(paths, pathsToSkip);
3110
+ }
3111
+ const validating = {};
3112
+
3113
+ for (let i = 0, len = paths.length; i < len; ++i) {
3114
+ const path = paths[i];
3115
+
3116
+ if (validating[path]) {
3117
+ continue;
3118
+ }
3119
+
3120
+ validating[path] = true;
3121
+
3122
+ const p = _this.$__schema.path(path);
3123
+ if (!p) {
3124
+ continue;
3125
+ }
3126
+ if (!_this.$isValid(path)) {
3127
+ continue;
3128
+ }
3129
+
3130
+ const val = _this.$__getValue(path);
3131
+ const err = p.doValidateSync(val, _this, {
3132
+ skipSchemaValidators: skipSchemaValidators[path],
3133
+ path: path,
3134
+ validateModifiedOnly: shouldValidateModifiedOnly
3135
+ });
3136
+ if (err) {
3137
+ const isSubdoc = p.$isSingleNested ||
3138
+ p.$isArraySubdocument ||
3139
+ p.$isMongooseDocumentArray;
3140
+ if (isSubdoc && err instanceof ValidationError) {
3141
+ continue;
3142
+ }
3143
+ _this.invalidate(path, err, undefined, true);
3144
+ }
3145
+ }
3146
+
3147
+ const err = _this.$__.validationError;
3148
+ _this.$__.validationError = undefined;
3149
+ _this.$emit('validate', _this);
3150
+ _this.constructor.emit('validate', _this);
3151
+
3152
+ if (err) {
3153
+ for (const key in err.errors) {
3154
+ // Make sure cast errors persist
3155
+ if (err.errors[key] instanceof MongooseError.CastError) {
3156
+ _this.invalidate(key, err.errors[key]);
3157
+ }
3158
+ }
3159
+ }
3160
+
3161
+ return err;
3162
+ };
3163
+
3164
+ /**
3165
+ * Marks a path as invalid, causing validation to fail.
3166
+ *
3167
+ * The `errorMsg` argument will become the message of the `ValidationError`.
3168
+ *
3169
+ * The `value` argument (if passed) will be available through the `ValidationError.value` property.
3170
+ *
3171
+ * doc.invalidate('size', 'must be less than 20', 14);
3172
+ *
3173
+ * doc.validate(function (err) {
3174
+ * console.log(err)
3175
+ * // prints
3176
+ * { message: 'Validation failed',
3177
+ * name: 'ValidationError',
3178
+ * errors:
3179
+ * { size:
3180
+ * { message: 'must be less than 20',
3181
+ * name: 'ValidatorError',
3182
+ * path: 'size',
3183
+ * type: 'user defined',
3184
+ * value: 14 } } }
3185
+ * })
3186
+ *
3187
+ * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array.
3188
+ * @param {String|Error} err the error which states the reason `path` was invalid
3189
+ * @param {Object|String|Number|any} val optional invalid value
3190
+ * @param {String} [kind] optional `kind` property for the error
3191
+ * @return {ValidationError} the current ValidationError, with all currently invalidated paths
3192
+ * @api public
3193
+ */
3194
+
3195
+ Document.prototype.invalidate = function(path, err, val, kind) {
3196
+ if (!this.$__.validationError) {
3197
+ this.$__.validationError = new ValidationError(this);
3198
+ }
3199
+
3200
+ if (this.$__.validationError.errors[path]) {
3201
+ return;
3202
+ }
3203
+
3204
+ if (!err || typeof err === 'string') {
3205
+ err = new ValidatorError({
3206
+ path: path,
3207
+ message: err,
3208
+ type: kind || 'user defined',
3209
+ value: val
3210
+ });
3211
+ }
3212
+
3213
+ if (this.$__.validationError === err) {
3214
+ return this.$__.validationError;
3215
+ }
3216
+
3217
+ this.$__.validationError.addError(path, err);
3218
+ return this.$__.validationError;
3219
+ };
3220
+
3221
+ /**
3222
+ * Marks a path as valid, removing existing validation errors.
3223
+ *
3224
+ * @param {String} path the field to mark as valid
3225
+ * @api public
3226
+ * @memberOf Document
3227
+ * @instance
3228
+ * @method $markValid
3229
+ */
3230
+
3231
+ Document.prototype.$markValid = function(path) {
3232
+ if (!this.$__.validationError || !this.$__.validationError.errors[path]) {
3233
+ return;
3234
+ }
3235
+
3236
+ delete this.$__.validationError.errors[path];
3237
+ if (Object.keys(this.$__.validationError.errors).length === 0) {
3238
+ this.$__.validationError = null;
3239
+ }
3240
+ };
3241
+
3242
+ /*!
3243
+ * ignore
3244
+ */
3245
+
3246
+ function _markValidSubpaths(doc, path) {
3247
+ if (!doc.$__.validationError) {
3248
+ return;
3249
+ }
3250
+
3251
+ const keys = Object.keys(doc.$__.validationError.errors);
3252
+ for (const key of keys) {
3253
+ if (key.startsWith(path + '.')) {
3254
+ delete doc.$__.validationError.errors[key];
3255
+ }
3256
+ }
3257
+ if (Object.keys(doc.$__.validationError.errors).length === 0) {
3258
+ doc.$__.validationError = null;
3259
+ }
3260
+ }
3261
+
3262
+ /*!
3263
+ * ignore
3264
+ */
3265
+
3266
+ function _checkImmutableSubpaths(subdoc, schematype, priorVal) {
3267
+ const schema = schematype.schema;
3268
+ if (schema == null) {
3269
+ return;
3270
+ }
3271
+
3272
+ for (const key of Object.keys(schema.paths)) {
3273
+ const path = schema.paths[key];
3274
+ if (path.$immutableSetter == null) {
3275
+ continue;
3276
+ }
3277
+ const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key);
3278
+ // Calling immutableSetter with `oldVal` even though it expects `newVal`
3279
+ // is intentional. That's because `$immutableSetter` compares its param
3280
+ // to the current value.
3281
+ path.$immutableSetter.call(subdoc, oldVal);
3282
+ }
3283
+ }
3284
+
3285
+ /**
3286
+ * Saves this document by inserting a new document into the database if [document.isNew](#document_Document-isNew) is `true`,
3287
+ * or sends an [updateOne](#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case.
3288
+ *
3289
+ * #### Example:
3290
+ *
3291
+ * product.sold = Date.now();
3292
+ * product = await product.save();
3293
+ *
3294
+ * If save is successful, the returned promise will fulfill with the document
3295
+ * saved.
3296
+ *
3297
+ * #### Example:
3298
+ *
3299
+ * const newProduct = await product.save();
3300
+ * newProduct === product; // true
3301
+ *
3302
+ * @param {Object} [options] options optional options
3303
+ * @param {Session} [options.session=null] the [session](https://www.mongodb.com/docs/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](#document_Document-$session).
3304
+ * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](https://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead.
3305
+ * @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
3306
+ * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
3307
+ * @param {Number|String} [options.w] set the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
3308
+ * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
3309
+ * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern).
3310
+ * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://www.mongodb.com/docs/manual/reference/limits/#Restrictions-on-Field-Names)
3311
+ * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this `save()`.
3312
+ * @param {Function} [fn] optional callback
3313
+ * @method save
3314
+ * @memberOf Document
3315
+ * @instance
3316
+ * @throws {DocumentNotFoundError} if this [save updates an existing document](#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating).
3317
+ * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise.
3318
+ * @api public
3319
+ * @see middleware https://mongoosejs.com/docs/middleware.html
3320
+ */
3321
+
3322
+ /**
3323
+ * Checks if a path is invalid
3324
+ *
3325
+ * @param {String|String[]} [path] the field to check. If unset will always return "false"
3326
+ * @method $isValid
3327
+ * @memberOf Document
3328
+ * @instance
3329
+ * @api private
3330
+ */
3331
+
3332
+ Document.prototype.$isValid = function(path) {
3333
+ if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) {
3334
+ return true;
3335
+ }
3336
+ if (path == null) {
3337
+ return false;
3338
+ }
3339
+
3340
+ if (path.indexOf(' ') !== -1) {
3341
+ path = path.split(' ');
3342
+ }
3343
+ if (Array.isArray(path)) {
3344
+ return path.some(p => this.$__.validationError.errors[p] == null);
3345
+ }
3346
+
3347
+ return this.$__.validationError.errors[path] == null;
3348
+ };
3349
+
3350
+ /**
3351
+ * Resets the internal modified state of this document.
3352
+ *
3353
+ * @api private
3354
+ * @return {Document} this
3355
+ * @method $__reset
3356
+ * @memberOf Document
3357
+ * @instance
3358
+ */
3359
+
3360
+ Document.prototype.$__reset = function reset() {
3361
+ let _this = this;
3362
+
3363
+ // Skip for subdocuments
3364
+ const subdocs = this.$parent() === this ? this.$getAllSubdocs() : [];
3365
+ const resetArrays = new Set();
3366
+ for (const subdoc of subdocs) {
3367
+ const fullPathWithIndexes = subdoc.$__fullPathWithIndexes();
3368
+ if (this.isModified(fullPathWithIndexes) || isParentInit(fullPathWithIndexes)) {
3369
+ subdoc.$__reset();
3370
+ if (subdoc.$isDocumentArrayElement) {
3371
+ if (!resetArrays.has(subdoc.parentArray())) {
3372
+ const array = subdoc.parentArray();
3373
+ this.$__.activePaths.clearPath(fullPathWithIndexes.replace(/\.\d+$/, '').slice(-subdoc.$basePath - 1));
3374
+ array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol];
3375
+ array[arrayAtomicsSymbol] = {};
3376
+
3377
+ resetArrays.add(array);
3378
+ }
3379
+ } else {
3380
+ const parent = subdoc.$parent();
3381
+ if (parent === this) {
3382
+ this.$__.activePaths.clearPath(subdoc.$basePath);
3383
+ } else if (parent != null && parent.$isSubdocument) {
3384
+ // If map path underneath subdocument, may end up with a case where
3385
+ // map path is modified but parent still needs to be reset. See gh-10295
3386
+ parent.$__reset();
3387
+ }
3388
+ }
3389
+ }
3390
+ }
3391
+
3392
+ function isParentInit(path) {
3393
+ path = path.indexOf('.') === -1 ? [path] : path.split('.');
3394
+ let cur = '';
3395
+ for (let i = 0; i < path.length; ++i) {
3396
+ cur += (cur.length ? '.' : '') + path[i];
3397
+ if (_this.$__.activePaths[cur] === 'init') {
3398
+ return true;
3399
+ }
3400
+ }
3401
+
3402
+ return false;
3403
+ }
3404
+
3405
+ // clear atomics
3406
+ this.$__dirty().forEach(function(dirt) {
3407
+ const type = dirt.value;
3408
+
3409
+ if (type && type[arrayAtomicsSymbol]) {
3410
+ type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol];
3411
+ type[arrayAtomicsSymbol] = {};
3412
+ }
3413
+ });
3414
+
3415
+ this.$__.backup = {};
3416
+ this.$__.backup.activePaths = {
3417
+ modify: Object.assign({}, this.$__.activePaths.getStatePaths('modify')),
3418
+ default: Object.assign({}, this.$__.activePaths.getStatePaths('default'))
3419
+ };
3420
+ this.$__.backup.validationError = this.$__.validationError;
3421
+ this.$__.backup.errors = this.$errors;
3422
+
3423
+ // Clear 'dirty' cache
3424
+ this.$__.activePaths.clear('modify');
3425
+ this.$__.activePaths.clear('default');
3426
+ this.$__.validationError = undefined;
3427
+ this.$errors = undefined;
3428
+ _this = this;
3429
+ this.$__schema.requiredPaths().forEach(function(path) {
3430
+ _this.$__.activePaths.require(path);
3431
+ });
3432
+
3433
+ return this;
3434
+ };
3435
+
3436
+ /*!
3437
+ * ignore
3438
+ */
3439
+
3440
+ Document.prototype.$__undoReset = function $__undoReset() {
3441
+ if (this.$__.backup == null || this.$__.backup.activePaths == null) {
3442
+ return;
3443
+ }
3444
+
3445
+ this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify;
3446
+ this.$__.activePaths.states.default = this.$__.backup.activePaths.default;
3447
+
3448
+ this.$__.validationError = this.$__.backup.validationError;
3449
+ this.$errors = this.$__.backup.errors;
3450
+
3451
+ for (const dirt of this.$__dirty()) {
3452
+ const type = dirt.value;
3453
+
3454
+ if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) {
3455
+ type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol];
3456
+ }
3457
+ }
3458
+
3459
+ for (const subdoc of this.$getAllSubdocs()) {
3460
+ subdoc.$__undoReset();
3461
+ }
3462
+ };
3463
+
3464
+ /**
3465
+ * Returns this documents dirty paths / vals.
3466
+ *
3467
+ * @return {Array}
3468
+ * @api private
3469
+ * @method $__dirty
3470
+ * @memberOf Document
3471
+ * @instance
3472
+ */
3473
+
3474
+ Document.prototype.$__dirty = function() {
3475
+ const _this = this;
3476
+ let all = this.$__.activePaths.map('modify', function(path) {
3477
+ return {
3478
+ path: path,
3479
+ value: _this.$__getValue(path),
3480
+ schema: _this.$__path(path)
3481
+ };
3482
+ });
3483
+
3484
+ // gh-2558: if we had to set a default and the value is not undefined,
3485
+ // we have to save as well
3486
+ all = all.concat(this.$__.activePaths.map('default', function(path) {
3487
+ if (path === '_id' || _this.$__getValue(path) == null) {
3488
+ return;
3489
+ }
3490
+ return {
3491
+ path: path,
3492
+ value: _this.$__getValue(path),
3493
+ schema: _this.$__path(path)
3494
+ };
3495
+ }));
3496
+
3497
+ const allPaths = new Map(all.filter((el) => el != null).map((el) => [el.path, el.value]));
3498
+ // Ignore "foo.a" if "foo" is dirty already.
3499
+ const minimal = [];
3500
+
3501
+ all.forEach(function(item) {
3502
+ if (!item) {
3503
+ return;
3504
+ }
3505
+
3506
+ let top = null;
3507
+
3508
+ const array = parentPaths(item.path);
3509
+ for (let i = 0; i < array.length - 1; i++) {
3510
+ if (allPaths.has(array[i])) {
3511
+ top = allPaths.get(array[i]);
3512
+ break;
3513
+ }
3514
+ }
3515
+ if (top == null) {
3516
+ minimal.push(item);
3517
+ } else if (top != null &&
3518
+ top[arrayAtomicsSymbol] != null &&
3519
+ top.hasAtomics()) {
3520
+ // special case for top level MongooseArrays
3521
+ // the `top` array itself and a sub path of `top` are being set.
3522
+ // the only way to honor all of both modifications is through a $set
3523
+ // of entire array.
3524
+ top[arrayAtomicsSymbol] = {};
3525
+ top[arrayAtomicsSymbol].$set = top;
3526
+ }
3527
+ });
3528
+ return minimal;
3529
+ };
3530
+
3531
+ /**
3532
+ * Assigns/compiles `schema` into this documents prototype.
3533
+ *
3534
+ * @param {Schema} schema
3535
+ * @api private
3536
+ * @method $__setSchema
3537
+ * @memberOf Document
3538
+ * @instance
3539
+ */
3540
+
3541
+ Document.prototype.$__setSchema = function(schema) {
3542
+ compile(schema.tree, this, undefined, schema.options);
3543
+
3544
+ // Apply default getters if virtual doesn't have any (gh-6262)
3545
+ for (const key of Object.keys(schema.virtuals)) {
3546
+ schema.virtuals[key]._applyDefaultGetters();
3547
+ }
3548
+ if (schema.path('schema') == null) {
3549
+ this.schema = schema;
3550
+ }
3551
+ this.$__schema = schema;
3552
+ this[documentSchemaSymbol] = schema;
3553
+ };
3554
+
3555
+
3556
+ /**
3557
+ * Get active path that were changed and are arrays
3558
+ *
3559
+ * @return {Array}
3560
+ * @api private
3561
+ * @method $__getArrayPathsToValidate
3562
+ * @memberOf Document
3563
+ * @instance
3564
+ */
3565
+
3566
+ Document.prototype.$__getArrayPathsToValidate = function() {
3567
+ DocumentArray || (DocumentArray = require('./types/DocumentArray'));
3568
+
3569
+ // validate all document arrays.
3570
+ return this.$__.activePaths
3571
+ .map('init', 'modify', function(i) {
3572
+ return this.$__getValue(i);
3573
+ }.bind(this))
3574
+ .filter(function(val) {
3575
+ return val && Array.isArray(val) && utils.isMongooseDocumentArray(val) && val.length;
3576
+ }).reduce(function(seed, array) {
3577
+ return seed.concat(array);
3578
+ }, [])
3579
+ .filter(function(doc) {
3580
+ return doc;
3581
+ });
3582
+ };
3583
+
3584
+
3585
+ /**
3586
+ * Get all subdocs (by bfs)
3587
+ *
3588
+ * @return {Array}
3589
+ * @api public
3590
+ * @method $getAllSubdocs
3591
+ * @memberOf Document
3592
+ * @instance
3593
+ */
3594
+
3595
+ Document.prototype.$getAllSubdocs = function() {
3596
+ DocumentArray || (DocumentArray = require('./types/DocumentArray'));
3597
+ Embedded = Embedded || require('./types/ArraySubdocument');
3598
+
3599
+ function docReducer(doc, seed, path) {
3600
+ let val = doc;
3601
+ let isNested = false;
3602
+ if (path) {
3603
+ if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) {
3604
+ val = doc._doc[path];
3605
+ } else if (doc instanceof Document && doc[documentSchemaSymbol].nested[path]) {
3606
+ val = doc._doc[path];
3607
+ isNested = true;
3608
+ } else {
3609
+ val = doc[path];
3610
+ }
3611
+ }
3612
+ if (val instanceof Embedded) {
3613
+ seed.push(val);
3614
+ } else if (val instanceof Map) {
3615
+ seed = Array.from(val.keys()).reduce(function(seed, path) {
3616
+ return docReducer(val.get(path), seed, null);
3617
+ }, seed);
3618
+ } else if (val && !Array.isArray(val) && val.$isSingleNested) {
3619
+ seed = Object.keys(val._doc).reduce(function(seed, path) {
3620
+ return docReducer(val, seed, path);
3621
+ }, seed);
3622
+ seed.push(val);
3623
+ } else if (val && utils.isMongooseDocumentArray(val)) {
3624
+ val.forEach(function _docReduce(doc) {
3625
+ if (!doc || !doc._doc) {
3626
+ return;
3627
+ }
3628
+ seed = Object.keys(doc._doc).reduce(function(seed, path) {
3629
+ return docReducer(doc._doc, seed, path);
3630
+ }, seed);
3631
+ if (doc instanceof Embedded) {
3632
+ seed.push(doc);
3633
+ }
3634
+ });
3635
+ } else if (isNested && val != null) {
3636
+ for (const path of Object.keys(val)) {
3637
+ docReducer(val, seed, path);
3638
+ }
3639
+ }
3640
+ return seed;
3641
+ }
3642
+
3643
+ const subDocs = [];
3644
+ for (const path of Object.keys(this._doc)) {
3645
+ docReducer(this, subDocs, path);
3646
+ }
3647
+
3648
+ return subDocs;
3649
+ };
3650
+
3651
+ /*!
3652
+ * Runs queued functions
3653
+ */
3654
+
3655
+ function applyQueue(doc) {
3656
+ const q = doc.$__schema && doc.$__schema.callQueue;
3657
+ if (!q.length) {
3658
+ return;
3659
+ }
3660
+
3661
+ for (const pair of q) {
3662
+ if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') {
3663
+ doc[pair[0]].apply(doc, pair[1]);
3664
+ }
3665
+ }
3666
+ }
3667
+
3668
+ /*!
3669
+ * ignore
3670
+ */
3671
+
3672
+ Document.prototype.$__handleReject = function handleReject(err) {
3673
+ // emit on the Model if listening
3674
+ if (this.$listeners('error').length) {
3675
+ this.$emit('error', err);
3676
+ } else if (this.constructor.listeners && this.constructor.listeners('error').length) {
3677
+ this.constructor.emit('error', err);
3678
+ }
3679
+ };
3680
+
3681
+ /**
3682
+ * Internal helper for toObject() and toJSON() that doesn't manipulate options
3683
+ *
3684
+ * @return {Object}
3685
+ * @api private
3686
+ * @method $toObject
3687
+ * @memberOf Document
3688
+ * @instance
3689
+ */
3690
+
3691
+ Document.prototype.$toObject = function(options, json) {
3692
+ let defaultOptions = {
3693
+ transform: true,
3694
+ flattenDecimals: true
3695
+ };
3696
+
3697
+ const path = json ? 'toJSON' : 'toObject';
3698
+ const baseOptions = this.constructor &&
3699
+ this.constructor.base &&
3700
+ this.constructor.base.options &&
3701
+ get(this.constructor.base.options, path) || {};
3702
+ const schemaOptions = this.$__schema && this.$__schema.options || {};
3703
+ // merge base default options with Schema's set default options if available.
3704
+ // `clone` is necessary here because `utils.options` directly modifies the second input.
3705
+ defaultOptions = utils.options(defaultOptions, clone(baseOptions));
3706
+ defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {}));
3707
+
3708
+ // If options do not exist or is not an object, set it to empty object
3709
+ options = utils.isPOJO(options) ? { ...options } : {};
3710
+ options._calledWithOptions = options._calledWithOptions || { ...options };
3711
+
3712
+ let _minimize;
3713
+ if (options._calledWithOptions.minimize != null) {
3714
+ _minimize = options.minimize;
3715
+ } else if (defaultOptions.minimize != null) {
3716
+ _minimize = defaultOptions.minimize;
3717
+ } else {
3718
+ _minimize = schemaOptions.minimize;
3719
+ }
3720
+
3721
+ let flattenMaps;
3722
+ if (options._calledWithOptions.flattenMaps != null) {
3723
+ flattenMaps = options.flattenMaps;
3724
+ } else if (defaultOptions.flattenMaps != null) {
3725
+ flattenMaps = defaultOptions.flattenMaps;
3726
+ } else {
3727
+ flattenMaps = schemaOptions.flattenMaps;
3728
+ }
3729
+
3730
+ // The original options that will be passed to `clone()`. Important because
3731
+ // `clone()` will recursively call `$toObject()` on embedded docs, so we
3732
+ // need the original options the user passed in, plus `_isNested` and
3733
+ // `_parentOptions` for checking whether we need to depopulate.
3734
+ const cloneOptions = Object.assign({}, options, {
3735
+ _isNested: true,
3736
+ json: json,
3737
+ minimize: _minimize,
3738
+ flattenMaps: flattenMaps,
3739
+ _seen: (options && options._seen) || new Map()
3740
+ });
3741
+
3742
+ if (utils.hasUserDefinedProperty(options, 'getters')) {
3743
+ cloneOptions.getters = options.getters;
3744
+ }
3745
+ if (utils.hasUserDefinedProperty(options, 'virtuals')) {
3746
+ cloneOptions.virtuals = options.virtuals;
3747
+ }
3748
+
3749
+ const depopulate = options.depopulate ||
3750
+ (options._parentOptions && options._parentOptions.depopulate || false);
3751
+ // _isNested will only be true if this is not the top level document, we
3752
+ // should never depopulate the top-level document
3753
+ if (depopulate && options._isNested && this.$__.wasPopulated) {
3754
+ return clone(this.$__.wasPopulated.value || this._id, cloneOptions);
3755
+ }
3756
+
3757
+ // merge default options with input options.
3758
+ options = utils.options(defaultOptions, options);
3759
+ options._isNested = true;
3760
+ options.json = json;
3761
+ options.minimize = _minimize;
3762
+
3763
+ cloneOptions._parentOptions = options;
3764
+ cloneOptions._skipSingleNestedGetters = false;
3765
+
3766
+ const gettersOptions = Object.assign({}, cloneOptions);
3767
+ gettersOptions._skipSingleNestedGetters = true;
3768
+
3769
+ // remember the root transform function
3770
+ // to save it from being overwritten by sub-transform functions
3771
+ const originalTransform = options.transform;
3772
+
3773
+ let ret = clone(this._doc, cloneOptions) || {};
3774
+
3775
+ if (options.getters) {
3776
+ applyGetters(this, ret, gettersOptions);
3777
+
3778
+ if (options.minimize) {
3779
+ ret = minimize(ret) || {};
3780
+ }
3781
+ }
3782
+
3783
+ if (options.virtuals || (options.getters && options.virtuals !== false)) {
3784
+ applyVirtuals(this, ret, gettersOptions, options);
3785
+ }
3786
+
3787
+ if (options.versionKey === false && this.$__schema.options.versionKey) {
3788
+ delete ret[this.$__schema.options.versionKey];
3789
+ }
3790
+
3791
+ let transform = options.transform;
3792
+
3793
+ // In the case where a subdocument has its own transform function, we need to
3794
+ // check and see if the parent has a transform (options.transform) and if the
3795
+ // child schema has a transform (this.schema.options.toObject) In this case,
3796
+ // we need to adjust options.transform to be the child schema's transform and
3797
+ // not the parent schema's
3798
+ if (transform) {
3799
+ applySchemaTypeTransforms(this, ret);
3800
+ }
3801
+
3802
+ if (options.useProjection) {
3803
+ omitDeselectedFields(this, ret);
3804
+ }
3805
+
3806
+ if (transform === true || (schemaOptions.toObject && transform)) {
3807
+ const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject;
3808
+
3809
+ if (opts) {
3810
+ transform = (typeof options.transform === 'function' ? options.transform : opts.transform);
3811
+ }
3812
+ } else {
3813
+ options.transform = originalTransform;
3814
+ }
3815
+
3816
+ if (typeof transform === 'function') {
3817
+ const xformed = transform(this, ret, options);
3818
+ if (typeof xformed !== 'undefined') {
3819
+ ret = xformed;
3820
+ }
3821
+ }
3822
+
3823
+ return ret;
3824
+ };
3825
+
3826
+ /**
3827
+ * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)).
3828
+ *
3829
+ * Buffers are converted to instances of [mongodb.Binary](https://mongodb.github.io/node-mongodb-native/4.9/classes/Binary.html) for proper storage.
3830
+ *
3831
+ * #### Getters/Virtuals
3832
+ *
3833
+ * Example of only applying path getters
3834
+ *
3835
+ * doc.toObject({ getters: true, virtuals: false })
3836
+ *
3837
+ * Example of only applying virtual getters
3838
+ *
3839
+ * doc.toObject({ virtuals: true })
3840
+ *
3841
+ * Example of applying both path and virtual getters
3842
+ *
3843
+ * doc.toObject({ getters: true })
3844
+ *
3845
+ * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument.
3846
+ *
3847
+ * schema.set('toObject', { virtuals: true })
3848
+ *
3849
+ * #### Transform:
3850
+ *
3851
+ * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function.
3852
+ *
3853
+ * Transform functions receive three arguments
3854
+ *
3855
+ * function (doc, ret, options) {}
3856
+ *
3857
+ * - `doc` The mongoose document which is being converted
3858
+ * - `ret` The plain object representation which has been converted
3859
+ * - `options` The options in use (either schema options or the options passed inline)
3860
+ *
3861
+ * #### Example:
3862
+ *
3863
+ * // specify the transform schema option
3864
+ * if (!schema.options.toObject) schema.options.toObject = {};
3865
+ * schema.options.toObject.transform = function (doc, ret, options) {
3866
+ * // remove the _id of every document before returning the result
3867
+ * delete ret._id;
3868
+ * return ret;
3869
+ * }
3870
+ *
3871
+ * // without the transformation in the schema
3872
+ * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
3873
+ *
3874
+ * // with the transformation
3875
+ * doc.toObject(); // { name: 'Wreck-it Ralph' }
3876
+ *
3877
+ * With transformations we can do a lot more than remove properties. We can even return completely new customized objects:
3878
+ *
3879
+ * if (!schema.options.toObject) schema.options.toObject = {};
3880
+ * schema.options.toObject.transform = function (doc, ret, options) {
3881
+ * return { movie: ret.name }
3882
+ * }
3883
+ *
3884
+ * // without the transformation in the schema
3885
+ * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
3886
+ *
3887
+ * // with the transformation
3888
+ * doc.toObject(); // { movie: 'Wreck-it Ralph' }
3889
+ *
3890
+ * _Note: if a transform function returns `undefined`, the return value will be ignored._
3891
+ *
3892
+ * Transformations may also be applied inline, overridding any transform set in the options:
3893
+ *
3894
+ * function xform (doc, ret, options) {
3895
+ * return { inline: ret.name, custom: true }
3896
+ * }
3897
+ *
3898
+ * // pass the transform as an inline option
3899
+ * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
3900
+ *
3901
+ * If you want to skip transformations, use `transform: false`:
3902
+ *
3903
+ * schema.options.toObject.hide = '_id';
3904
+ * schema.options.toObject.transform = function (doc, ret, options) {
3905
+ * if (options.hide) {
3906
+ * options.hide.split(' ').forEach(function (prop) {
3907
+ * delete ret[prop];
3908
+ * });
3909
+ * }
3910
+ * return ret;
3911
+ * }
3912
+ *
3913
+ * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
3914
+ * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
3915
+ * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
3916
+ * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }
3917
+ *
3918
+ * If you pass a transform in `toObject()` options, Mongoose will apply the transform
3919
+ * to [subdocuments](/docs/subdocs.html) in addition to the top-level document.
3920
+ * Similarly, `transform: false` skips transforms for all subdocuments.
3921
+ * Note that this behavior is different for transforms defined in the schema:
3922
+ * if you define a transform in `schema.options.toObject.transform`, that transform
3923
+ * will **not** apply to subdocuments.
3924
+ *
3925
+ * const memberSchema = new Schema({ name: String, email: String });
3926
+ * const groupSchema = new Schema({ members: [memberSchema], name: String, email });
3927
+ * const Group = mongoose.model('Group', groupSchema);
3928
+ *
3929
+ * const doc = new Group({
3930
+ * name: 'Engineering',
3931
+ * email: 'dev@mongoosejs.io',
3932
+ * members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
3933
+ * });
3934
+ *
3935
+ * // Removes `email` from both top-level document **and** array elements
3936
+ * // { name: 'Engineering', members: [{ name: 'Val' }] }
3937
+ * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });
3938
+ *
3939
+ * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions.
3940
+ *
3941
+ * See [schema options](/docs/guide.html#toObject) for some more details.
3942
+ *
3943
+ * _During save, no custom options are applied to the document before being sent to the database._
3944
+ *
3945
+ * @param {Object} [options]
3946
+ * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals
3947
+ * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals
3948
+ * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`.
3949
+ * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output
3950
+ * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object
3951
+ * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths.
3952
+ * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output
3953
+ * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`.
3954
+ * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema.
3955
+ * @return {Object} js object (not a POJO)
3956
+ * @see mongodb.Binary https://mongodb.github.io/node-mongodb-native/4.9/classes/Binary.html
3957
+ * @api public
3958
+ * @memberOf Document
3959
+ * @instance
3960
+ */
3961
+
3962
+ Document.prototype.toObject = function(options) {
3963
+ return this.$toObject(options);
3964
+ };
3965
+
3966
+ /**
3967
+ * Minimizes an object, removing undefined values and empty objects
3968
+ *
3969
+ * @param {Object} object to minimize
3970
+ * @return {Object}
3971
+ * @api private
3972
+ */
3973
+
3974
+ function minimize(obj) {
3975
+ const keys = Object.keys(obj);
3976
+ let i = keys.length;
3977
+ let hasKeys;
3978
+ let key;
3979
+ let val;
3980
+
3981
+ while (i--) {
3982
+ key = keys[i];
3983
+ val = obj[key];
3984
+
3985
+ if (utils.isPOJO(val)) {
3986
+ obj[key] = minimize(val);
3987
+ }
3988
+
3989
+ if (undefined === obj[key]) {
3990
+ delete obj[key];
3991
+ continue;
3992
+ }
3993
+
3994
+ hasKeys = true;
3995
+ }
3996
+
3997
+ return hasKeys
3998
+ ? obj
3999
+ : undefined;
4000
+ }
4001
+
4002
+ /*!
4003
+ * Applies virtuals properties to `json`.
4004
+ */
4005
+
4006
+ function applyVirtuals(self, json, options, toObjectOptions) {
4007
+ const schema = self.$__schema;
4008
+ const paths = Object.keys(schema.virtuals);
4009
+ let i = paths.length;
4010
+ const numPaths = i;
4011
+ let path;
4012
+ let assignPath;
4013
+ let cur = self._doc;
4014
+ let v;
4015
+ const aliases = typeof (toObjectOptions && toObjectOptions.aliases) === 'boolean'
4016
+ ? toObjectOptions.aliases
4017
+ : true;
4018
+
4019
+ options = options || {};
4020
+ let virtualsToApply = null;
4021
+ if (Array.isArray(options.virtuals)) {
4022
+ virtualsToApply = new Set(options.virtuals);
4023
+ } else if (options.virtuals && options.virtuals.pathsToSkip) {
4024
+ virtualsToApply = new Set(paths);
4025
+ for (let i = 0; i < options.virtuals.pathsToSkip.length; i++) {
4026
+ if (virtualsToApply.has(options.virtuals.pathsToSkip[i])) {
4027
+ virtualsToApply.delete(options.virtuals.pathsToSkip[i]);
4028
+ }
4029
+ }
4030
+ }
4031
+
4032
+ if (!cur) {
4033
+ return json;
4034
+ }
4035
+
4036
+ for (i = 0; i < numPaths; ++i) {
4037
+ path = paths[i];
4038
+
4039
+ if (virtualsToApply != null && !virtualsToApply.has(path)) {
4040
+ continue;
4041
+ }
4042
+
4043
+ // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })`
4044
+ if (!aliases && schema.aliases.hasOwnProperty(path)) {
4045
+ continue;
4046
+ }
4047
+
4048
+ // We may be applying virtuals to a nested object, for example if calling
4049
+ // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`,
4050
+ // will be a trailing substring of the `path`.
4051
+ assignPath = path;
4052
+ if (options.path != null) {
4053
+ if (!path.startsWith(options.path + '.')) {
4054
+ continue;
4055
+ }
4056
+ assignPath = path.substring(options.path.length + 1);
4057
+ }
4058
+ const parts = assignPath.split('.');
4059
+ v = clone(self.get(path), options);
4060
+ if (v === void 0) {
4061
+ continue;
4062
+ }
4063
+ const plen = parts.length;
4064
+ cur = json;
4065
+ for (let j = 0; j < plen - 1; ++j) {
4066
+ cur[parts[j]] = cur[parts[j]] || {};
4067
+ cur = cur[parts[j]];
4068
+ }
4069
+ cur[parts[plen - 1]] = v;
4070
+ }
4071
+
4072
+ return json;
4073
+ }
4074
+
4075
+
4076
+ /**
4077
+ * Applies virtuals properties to `json`.
4078
+ *
4079
+ * @param {Document} self
4080
+ * @param {Object} json
4081
+ * @param {Object} [options]
4082
+ * @return {Object} `json`
4083
+ * @api private
4084
+ */
4085
+
4086
+ function applyGetters(self, json, options) {
4087
+ const schema = self.$__schema;
4088
+ const paths = Object.keys(schema.paths);
4089
+ let i = paths.length;
4090
+ let path;
4091
+ let cur = self._doc;
4092
+ let v;
4093
+
4094
+ if (!cur) {
4095
+ return json;
4096
+ }
4097
+
4098
+ while (i--) {
4099
+ path = paths[i];
4100
+
4101
+ const parts = path.split('.');
4102
+
4103
+ const plen = parts.length;
4104
+ const last = plen - 1;
4105
+ let branch = json;
4106
+ let part;
4107
+ cur = self._doc;
4108
+
4109
+ if (!self.$__isSelected(path)) {
4110
+ continue;
4111
+ }
4112
+
4113
+ for (let ii = 0; ii < plen; ++ii) {
4114
+ part = parts[ii];
4115
+ v = cur[part];
4116
+ // If we've reached a non-object part of the branch, continuing would
4117
+ // cause "Cannot create property 'foo' on string 'bar'" error.
4118
+ // Necessary for mongoose-intl plugin re: gh-14446
4119
+ if (branch != null && typeof branch !== 'object') {
4120
+ break;
4121
+ } else if (ii === last) {
4122
+ const val = self.$get(path);
4123
+ branch[part] = clone(val, options);
4124
+ } else if (v == null) {
4125
+ if (part in cur) {
4126
+ branch[part] = v;
4127
+ }
4128
+ break;
4129
+ } else {
4130
+ branch = branch[part] || (branch[part] = {});
4131
+ }
4132
+ cur = v;
4133
+ }
4134
+ }
4135
+
4136
+ return json;
4137
+ }
4138
+
4139
+ /**
4140
+ * Applies schema type transforms to `json`.
4141
+ *
4142
+ * @param {Document} self
4143
+ * @param {Object} json
4144
+ * @return {Object} `json`
4145
+ * @api private
4146
+ */
4147
+
4148
+ function applySchemaTypeTransforms(self, json) {
4149
+ const schema = self.$__schema;
4150
+ const paths = Object.keys(schema.paths || {});
4151
+ const cur = self._doc;
4152
+
4153
+ if (!cur) {
4154
+ return json;
4155
+ }
4156
+
4157
+ for (const path of paths) {
4158
+ const schematype = schema.paths[path];
4159
+ if (typeof schematype.options.transform === 'function') {
4160
+ const val = self.$get(path);
4161
+ if (val === undefined) {
4162
+ continue;
4163
+ }
4164
+ const transformedValue = schematype.options.transform.call(self, val);
4165
+ throwErrorIfPromise(path, transformedValue);
4166
+ utils.setValue(path, transformedValue, json);
4167
+ } else if (schematype.$embeddedSchemaType != null &&
4168
+ typeof schematype.$embeddedSchemaType.options.transform === 'function') {
4169
+ const val = self.$get(path);
4170
+ if (val === undefined) {
4171
+ continue;
4172
+ }
4173
+ const vals = [].concat(val);
4174
+ const transform = schematype.$embeddedSchemaType.options.transform;
4175
+ for (let i = 0; i < vals.length; ++i) {
4176
+ const transformedValue = transform.call(self, vals[i]);
4177
+ vals[i] = transformedValue;
4178
+ throwErrorIfPromise(path, transformedValue);
4179
+ }
4180
+
4181
+ json[path] = vals;
4182
+ }
4183
+ }
4184
+
4185
+ return json;
4186
+ }
4187
+
4188
+ function throwErrorIfPromise(path, transformedValue) {
4189
+ if (isPromise(transformedValue)) {
4190
+ throw new Error('`transform` function must be synchronous, but the transform on path `' + path + '` returned a promise.');
4191
+ }
4192
+ }
4193
+
4194
+ /*!
4195
+ * ignore
4196
+ */
4197
+
4198
+ function omitDeselectedFields(self, json) {
4199
+ const schema = self.$__schema;
4200
+ const paths = Object.keys(schema.paths || {});
4201
+ const cur = self._doc;
4202
+
4203
+ if (!cur) {
4204
+ return json;
4205
+ }
4206
+
4207
+ let selected = self.$__.selected;
4208
+ if (selected === void 0) {
4209
+ selected = {};
4210
+ queryhelpers.applyPaths(selected, schema);
4211
+ }
4212
+ if (selected == null || Object.keys(selected).length === 0) {
4213
+ return json;
4214
+ }
4215
+
4216
+ for (const path of paths) {
4217
+ if (selected[path] != null && !selected[path]) {
4218
+ delete json[path];
4219
+ }
4220
+ }
4221
+
4222
+ return json;
4223
+ }
4224
+
4225
+ /**
4226
+ * The return value of this method is used in calls to [`JSON.stringify(doc)`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript#the-tojson-function).
4227
+ *
4228
+ * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument.
4229
+ *
4230
+ * schema.set('toJSON', { virtuals: true });
4231
+ *
4232
+ * There is one difference between `toJSON()` and `toObject()` options.
4233
+ * When you call `toJSON()`, the [`flattenMaps` option](./document.html#document_Document-toObject) defaults to `true`, because `JSON.stringify()` doesn't convert maps to objects by default.
4234
+ * When you call `toObject()`, the `flattenMaps` option is `false` by default.
4235
+ *
4236
+ * See [schema options](/docs/guide.html#toJSON) for more information on setting `toJSON` option defaults.
4237
+ *
4238
+ * @param {Object} options
4239
+ * @param {Boolean} [options.flattenMaps=true] if true, convert Maps to [POJOs](https://masteringjs.io/tutorials/fundamentals/pojo). Useful if you want to `JSON.stringify()` the result.
4240
+ * @return {Object}
4241
+ * @see Document#toObject #document_Document-toObject
4242
+ * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html
4243
+ * @api public
4244
+ * @memberOf Document
4245
+ * @instance
4246
+ */
4247
+
4248
+ Document.prototype.toJSON = function(options) {
4249
+ return this.$toObject(options, true);
4250
+ };
4251
+
4252
+
4253
+ Document.prototype.ownerDocument = function() {
4254
+ return this;
4255
+ };
4256
+
4257
+
4258
+ /**
4259
+ * If this document is a subdocument or populated document, returns the document's
4260
+ * parent. Returns the original document if there is no parent.
4261
+ *
4262
+ * @return {Document}
4263
+ * @api public
4264
+ * @method parent
4265
+ * @memberOf Document
4266
+ * @instance
4267
+ */
4268
+
4269
+ Document.prototype.parent = function() {
4270
+ if (this.$isSubdocument || this.$__.wasPopulated) {
4271
+ return this.$__.parent;
4272
+ }
4273
+ return this;
4274
+ };
4275
+
4276
+ /**
4277
+ * Alias for [`parent()`](#document_Document-parent). If this document is a subdocument or populated
4278
+ * document, returns the document's parent. Returns `undefined` otherwise.
4279
+ *
4280
+ * @return {Document}
4281
+ * @api public
4282
+ * @method $parent
4283
+ * @memberOf Document
4284
+ * @instance
4285
+ */
4286
+
4287
+ Document.prototype.$parent = Document.prototype.parent;
4288
+
4289
+ /**
4290
+ * Helper for console.log
4291
+ *
4292
+ * @return {String}
4293
+ * @api public
4294
+ * @method inspect
4295
+ * @memberOf Document
4296
+ * @instance
4297
+ */
4298
+
4299
+ Document.prototype.inspect = function(options) {
4300
+ const isPOJO = utils.isPOJO(options);
4301
+ let opts;
4302
+ if (isPOJO) {
4303
+ opts = options;
4304
+ opts.minimize = false;
4305
+ }
4306
+ const ret = this.toObject(opts);
4307
+
4308
+ if (ret == null) {
4309
+ // If `toObject()` returns null, `this` is still an object, so if `inspect()`
4310
+ // prints out null this can cause some serious confusion. See gh-7942.
4311
+ return 'MongooseDocument { ' + ret + ' }';
4312
+ }
4313
+
4314
+ return ret;
4315
+ };
4316
+
4317
+ if (inspect.custom) {
4318
+ // Avoid Node deprecation warning DEP0079
4319
+ Document.prototype[inspect.custom] = Document.prototype.inspect;
4320
+ }
4321
+
4322
+ /**
4323
+ * Helper for console.log
4324
+ *
4325
+ * @return {String}
4326
+ * @api public
4327
+ * @method toString
4328
+ * @memberOf Document
4329
+ * @instance
4330
+ */
4331
+
4332
+ Document.prototype.toString = function() {
4333
+ const ret = this.inspect();
4334
+ if (typeof ret === 'string') {
4335
+ return ret;
4336
+ }
4337
+ return inspect(ret);
4338
+ };
4339
+
4340
+ /**
4341
+ * Returns true if this document is equal to another document.
4342
+ *
4343
+ * Documents are considered equal when they have matching `_id`s, unless neither
4344
+ * document has an `_id`, in which case this function falls back to using
4345
+ * `deepEqual()`.
4346
+ *
4347
+ * @param {Document} [doc] a document to compare. If falsy, will always return "false".
4348
+ * @return {Boolean}
4349
+ * @api public
4350
+ * @memberOf Document
4351
+ * @instance
4352
+ */
4353
+
4354
+ Document.prototype.equals = function(doc) {
4355
+ if (!doc) {
4356
+ return false;
4357
+ }
4358
+
4359
+ const tid = this.$__getValue('_id');
4360
+ const docid = doc.$__ != null ? doc.$__getValue('_id') : doc;
4361
+ if (!tid && !docid) {
4362
+ return deepEqual(this, doc);
4363
+ }
4364
+ return tid && tid.equals
4365
+ ? tid.equals(docid)
4366
+ : tid === docid;
4367
+ };
4368
+
4369
+ /**
4370
+ * Populates paths on an existing document.
4371
+ *
4372
+ * #### Example:
4373
+ *
4374
+ * // Given a document, `populate()` lets you pull in referenced docs
4375
+ * await doc.populate([
4376
+ * 'stories',
4377
+ * { path: 'fans', sort: { name: -1 } }
4378
+ * ]);
4379
+ * doc.populated('stories'); // Array of ObjectIds
4380
+ * doc.stories[0].title; // 'Casino Royale'
4381
+ * doc.populated('fans'); // Array of ObjectIds
4382
+ *
4383
+ * // If the referenced doc has been deleted, `populate()` will
4384
+ * // remove that entry from the array.
4385
+ * await Story.delete({ title: 'Casino Royale' });
4386
+ * await doc.populate('stories'); // Empty array
4387
+ *
4388
+ * // You can also pass additional query options to `populate()`,
4389
+ * // like projections:
4390
+ * await doc.populate('fans', '-email');
4391
+ * doc.fans[0].email // undefined because of 2nd param `select`
4392
+ *
4393
+ * @param {String|Object|Array} path either the path to populate or an object specifying all parameters, or either an array of those
4394
+ * @param {Object|String} [select] Field selection for the population query
4395
+ * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field.
4396
+ * @param {Object} [match] Conditions for the population query
4397
+ * @param {Object} [options] Options for the population query (sort, etc)
4398
+ * @param {String} [options.path=null] The path to populate.
4399
+ * @param {string|PopulateOptions} [options.populate=null] Recursively populate paths in the populated documents. See [deep populate docs](/docs/populate.html#deep-populate).
4400
+ * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries.
4401
+ * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options).
4402
+ * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
4403
+ * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://www.mongodb.com/docs/manual/tutorial/query-documents/), or a function that returns a filter object.
4404
+ * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document.
4405
+ * @param {Object} [options.options=null] Additional options like `limit` and `lean`.
4406
+ * @param {Function} [callback] Callback
4407
+ * @see population /docs/populate.html
4408
+ * @see Query#select #query_Query-select
4409
+ * @see Model.populate #model_Model-populate
4410
+ * @memberOf Document
4411
+ * @instance
4412
+ * @return {Promise|null} Returns a Promise if no `callback` is given.
4413
+ * @api public
4414
+ */
4415
+
4416
+ Document.prototype.populate = function populate() {
4417
+ const pop = {};
4418
+ const args = [...arguments];
4419
+ let fn;
4420
+
4421
+ if (args.length !== 0) {
4422
+ if (typeof args[args.length - 1] === 'function') {
4423
+ fn = args.pop();
4424
+ }
4425
+
4426
+ // use hash to remove duplicate paths
4427
+ const res = utils.populate.apply(null, args);
4428
+ for (const populateOptions of res) {
4429
+ pop[populateOptions.path] = populateOptions;
4430
+ }
4431
+ }
4432
+
4433
+ const paths = utils.object.vals(pop);
4434
+ let topLevelModel = this.constructor;
4435
+ if (this.$__isNested) {
4436
+ topLevelModel = this.$__[scopeSymbol].constructor;
4437
+ const nestedPath = this.$__.nestedPath;
4438
+ paths.forEach(function(populateOptions) {
4439
+ populateOptions.path = nestedPath + '.' + populateOptions.path;
4440
+ });
4441
+ }
4442
+
4443
+ // Use `$session()` by default if the document has an associated session
4444
+ // See gh-6754
4445
+ if (this.$session() != null) {
4446
+ const session = this.$session();
4447
+ paths.forEach(path => {
4448
+ if (path.options == null) {
4449
+ path.options = { session: session };
4450
+ return;
4451
+ }
4452
+ if (!('session' in path.options)) {
4453
+ path.options.session = session;
4454
+ }
4455
+ });
4456
+ }
4457
+
4458
+ paths.forEach(p => {
4459
+ p._localModel = topLevelModel;
4460
+ });
4461
+
4462
+ return topLevelModel.populate(this, paths, fn);
4463
+ };
4464
+
4465
+ /**
4466
+ * Gets all populated documents associated with this document.
4467
+ *
4468
+ * @api public
4469
+ * @return {Document[]} array of populated documents. Empty array if there are no populated documents associated with this document.
4470
+ * @memberOf Document
4471
+ * @method $getPopulatedDocs
4472
+ * @instance
4473
+ */
4474
+
4475
+ Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() {
4476
+ let keys = [];
4477
+ if (this.$__.populated != null) {
4478
+ keys = keys.concat(Object.keys(this.$__.populated));
4479
+ }
4480
+ let result = [];
4481
+ for (const key of keys) {
4482
+ const value = this.$get(key);
4483
+ if (Array.isArray(value)) {
4484
+ result = result.concat(value);
4485
+ } else if (value instanceof Document) {
4486
+ result.push(value);
4487
+ }
4488
+ }
4489
+ return result;
4490
+ };
4491
+
4492
+ /**
4493
+ * Gets _id(s) used during population of the given `path`.
4494
+ *
4495
+ * #### Example:
4496
+ *
4497
+ * const doc = await Model.findOne().populate('author');
4498
+ *
4499
+ * console.log(doc.author.name); // Dr.Seuss
4500
+ * console.log(doc.populated('author')); // '5144cf8050f071d979c118a7'
4501
+ *
4502
+ * If the path was not populated, returns `undefined`.
4503
+ *
4504
+ * @param {String} path
4505
+ * @param {Any} [val]
4506
+ * @param {Object} [options]
4507
+ * @return {Array|ObjectId|Number|Buffer|String|undefined}
4508
+ * @memberOf Document
4509
+ * @instance
4510
+ * @api public
4511
+ */
4512
+
4513
+ Document.prototype.populated = function(path, val, options) {
4514
+ // val and options are internal
4515
+ if (val == null || val === true) {
4516
+ if (!this.$__.populated) {
4517
+ return undefined;
4518
+ }
4519
+ if (typeof path !== 'string') {
4520
+ return undefined;
4521
+ }
4522
+
4523
+ // Map paths can be populated with either `path.$*` or just `path`
4524
+ const _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path;
4525
+
4526
+ const v = this.$__.populated[_path];
4527
+ if (v) {
4528
+ return val === true ? v : v.value;
4529
+ }
4530
+ return undefined;
4531
+ }
4532
+
4533
+ this.$__.populated || (this.$__.populated = {});
4534
+ this.$__.populated[path] = { value: val, options: options };
4535
+
4536
+ // If this was a nested populate, make sure each populated doc knows
4537
+ // about its populated children (gh-7685)
4538
+ const pieces = path.split('.');
4539
+ for (let i = 0; i < pieces.length - 1; ++i) {
4540
+ const subpath = pieces.slice(0, i + 1).join('.');
4541
+ const subdoc = this.$get(subpath);
4542
+ if (subdoc != null && subdoc.$__ != null && this.$populated(subpath)) {
4543
+ const rest = pieces.slice(i + 1).join('.');
4544
+ subdoc.$populated(rest, val, options);
4545
+ // No need to continue because the above recursion should take care of
4546
+ // marking the rest of the docs as populated
4547
+ break;
4548
+ }
4549
+ }
4550
+
4551
+ return val;
4552
+ };
4553
+
4554
+ /**
4555
+ * Alias of [`.populated`](#document_Document-populated).
4556
+ *
4557
+ * @method $populated
4558
+ * @memberOf Document
4559
+ * @api public
4560
+ */
4561
+
4562
+ Document.prototype.$populated = Document.prototype.populated;
4563
+
4564
+ /**
4565
+ * Throws an error if a given path is not populated
4566
+ *
4567
+ * #### Example:
4568
+ *
4569
+ * const doc = await Model.findOne().populate('author');
4570
+ *
4571
+ * doc.$assertPopulated('author'); // does not throw
4572
+ * doc.$assertPopulated('other path'); // throws an error
4573
+ *
4574
+ * // Manually populate and assert in one call. The following does
4575
+ * // `doc.$set({ likes })` before asserting.
4576
+ * doc.$assertPopulated('likes', { likes });
4577
+ *
4578
+ *
4579
+ * @param {String|String[]} path path or array of paths to check. `$assertPopulated` throws if any of the given paths is not populated.
4580
+ * @param {Object} [values] optional values to `$set()`. Convenient if you want to manually populate a path and assert that the path was populated in 1 call.
4581
+ * @return {Document} this
4582
+ * @memberOf Document
4583
+ * @method $assertPopulated
4584
+ * @instance
4585
+ * @api public
4586
+ */
4587
+
4588
+ Document.prototype.$assertPopulated = function $assertPopulated(path, values) {
4589
+ if (Array.isArray(path)) {
4590
+ path.forEach(p => this.$assertPopulated(p, values));
4591
+ return this;
4592
+ }
4593
+
4594
+ if (arguments.length > 1) {
4595
+ this.$set(values);
4596
+ }
4597
+
4598
+ if (!this.$populated(path)) {
4599
+ throw new MongooseError(`Expected path "${path}" to be populated`);
4600
+ }
4601
+
4602
+ return this;
4603
+ };
4604
+
4605
+ /**
4606
+ * Takes a populated field and returns it to its unpopulated state.
4607
+ *
4608
+ * #### Example:
4609
+ *
4610
+ * Model.findOne().populate('author').exec(function (err, doc) {
4611
+ * console.log(doc.author.name); // Dr.Seuss
4612
+ * console.log(doc.depopulate('author'));
4613
+ * console.log(doc.author); // '5144cf8050f071d979c118a7'
4614
+ * })
4615
+ *
4616
+ * If the path was not provided, then all populated fields are returned to their unpopulated state.
4617
+ *
4618
+ * @param {String|String[]} [path] Specific Path to depopulate. If unset, will depopulate all paths on the Document. Or multiple space-delimited paths.
4619
+ * @return {Document} this
4620
+ * @see Document.populate #document_Document-populate
4621
+ * @api public
4622
+ * @memberOf Document
4623
+ * @instance
4624
+ */
4625
+
4626
+ Document.prototype.depopulate = function(path) {
4627
+ if (typeof path === 'string') {
4628
+ path = path.indexOf(' ') === -1 ? [path] : path.split(' ');
4629
+ }
4630
+
4631
+ let populatedIds;
4632
+ const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : [];
4633
+ const populated = this.$__ && this.$__.populated || {};
4634
+
4635
+ if (arguments.length === 0) {
4636
+ // Depopulate all
4637
+ for (const virtualKey of virtualKeys) {
4638
+ delete this.$$populatedVirtuals[virtualKey];
4639
+ delete this._doc[virtualKey];
4640
+ delete populated[virtualKey];
4641
+ }
4642
+
4643
+ const keys = Object.keys(populated);
4644
+
4645
+ for (const key of keys) {
4646
+ populatedIds = this.$populated(key);
4647
+ if (!populatedIds) {
4648
+ continue;
4649
+ }
4650
+ delete populated[key];
4651
+ utils.setValue(key, populatedIds, this._doc);
4652
+ }
4653
+ return this;
4654
+ }
4655
+
4656
+ for (const singlePath of path) {
4657
+ populatedIds = this.$populated(singlePath);
4658
+ delete populated[singlePath];
4659
+
4660
+ if (virtualKeys.indexOf(singlePath) !== -1) {
4661
+ delete this.$$populatedVirtuals[singlePath];
4662
+ delete this._doc[singlePath];
4663
+ } else if (populatedIds) {
4664
+ utils.setValue(singlePath, populatedIds, this._doc);
4665
+ }
4666
+ }
4667
+ return this;
4668
+ };
4669
+
4670
+
4671
+ /**
4672
+ * Returns the full path to this document.
4673
+ *
4674
+ * @param {String} [path]
4675
+ * @return {String}
4676
+ * @api private
4677
+ * @method $__fullPath
4678
+ * @memberOf Document
4679
+ * @instance
4680
+ */
4681
+
4682
+ Document.prototype.$__fullPath = function(path) {
4683
+ // overridden in SubDocuments
4684
+ return path || '';
4685
+ };
4686
+
4687
+ /**
4688
+ * Returns the changes that happened to the document
4689
+ * in the format that will be sent to MongoDB.
4690
+ *
4691
+ * #### Example:
4692
+ *
4693
+ * const userSchema = new Schema({
4694
+ * name: String,
4695
+ * age: Number,
4696
+ * country: String
4697
+ * });
4698
+ * const User = mongoose.model('User', userSchema);
4699
+ * const user = await User.create({
4700
+ * name: 'Hafez',
4701
+ * age: 25,
4702
+ * country: 'Egypt'
4703
+ * });
4704
+ *
4705
+ * // returns an empty object, no changes happened yet
4706
+ * user.getChanges(); // { }
4707
+ *
4708
+ * user.country = undefined;
4709
+ * user.age = 26;
4710
+ *
4711
+ * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
4712
+ *
4713
+ * await user.save();
4714
+ *
4715
+ * user.getChanges(); // { }
4716
+ *
4717
+ * Modifying the object that `getChanges()` returns does not affect the document's
4718
+ * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose
4719
+ * will still send a `$set` to the server.
4720
+ *
4721
+ * @return {Object}
4722
+ * @api public
4723
+ * @method getChanges
4724
+ * @memberOf Document
4725
+ * @instance
4726
+ */
4727
+
4728
+ Document.prototype.getChanges = function() {
4729
+ const delta = this.$__delta();
4730
+ const changes = delta ? delta[1] : {};
4731
+ return changes;
4732
+ };
4733
+
4734
+ /**
4735
+ * Returns a copy of this document with a deep clone of `_doc` and `$__`.
4736
+ *
4737
+ * @return {Document} a copy of this document
4738
+ * @api public
4739
+ * @method $clone
4740
+ * @memberOf Document
4741
+ * @instance
4742
+ */
4743
+
4744
+ Document.prototype.$clone = function() {
4745
+ const Model = this.constructor;
4746
+ const clonedDoc = new Model();
4747
+ clonedDoc.$isNew = this.$isNew;
4748
+ if (this._doc) {
4749
+ clonedDoc._doc = clone(this._doc);
4750
+ }
4751
+ if (this.$__) {
4752
+ const Cache = this.$__.constructor;
4753
+ const clonedCache = new Cache();
4754
+ for (const key of Object.getOwnPropertyNames(this.$__)) {
4755
+ if (key === 'activePaths') {
4756
+ continue;
4757
+ }
4758
+ clonedCache[key] = clone(this.$__[key]);
4759
+ }
4760
+ Object.assign(clonedCache.activePaths, clone({ ...this.$__.activePaths }));
4761
+ clonedDoc.$__ = clonedCache;
4762
+ }
4763
+ return clonedDoc;
4764
+ };
4765
+
4766
+ /*!
4767
+ * Module exports.
4768
+ */
4769
+
4770
+ Document.ValidationError = ValidationError;
4771
+ module.exports = exports = Document;