@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,1014 @@
1
+ 'use strict';
2
+
3
+ const Document = require('../../../document');
4
+ const ArraySubdocument = require('../../ArraySubdocument');
5
+ const cleanModifiedSubpaths = require('../../../helpers/document/cleanModifiedSubpaths');
6
+ const internalToObjectOptions = require('../../../options').internalToObjectOptions;
7
+ const mpath = require('mpath');
8
+ const utils = require('../../../utils');
9
+ const isBsonType = require('../../../helpers/isBsonType');
10
+
11
+ const arrayAtomicsSymbol = require('../../../helpers/symbols').arrayAtomicsSymbol;
12
+ const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
13
+ const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
14
+ const arraySchemaSymbol = require('../../../helpers/symbols').arraySchemaSymbol;
15
+ const populateModelSymbol = require('../../../helpers/symbols').populateModelSymbol;
16
+ const slicedSymbol = Symbol('mongoose#Array#sliced');
17
+
18
+ const _basePush = Array.prototype.push;
19
+
20
+ /*!
21
+ * ignore
22
+ */
23
+
24
+ const methods = {
25
+ /**
26
+ * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.
27
+ *
28
+ * If no atomics exist, we return all array values after conversion.
29
+ *
30
+ * @return {Array}
31
+ * @method $__getAtomics
32
+ * @memberOf MongooseArray
33
+ * @instance
34
+ * @api private
35
+ */
36
+
37
+ $__getAtomics() {
38
+ const ret = [];
39
+ const keys = Object.keys(this[arrayAtomicsSymbol] || {});
40
+ let i = keys.length;
41
+
42
+ const opts = Object.assign({}, internalToObjectOptions, { _isNested: true });
43
+
44
+ if (i === 0) {
45
+ ret[0] = ['$set', this.toObject(opts)];
46
+ return ret;
47
+ }
48
+
49
+ while (i--) {
50
+ const op = keys[i];
51
+ let val = this[arrayAtomicsSymbol][op];
52
+
53
+ // the atomic values which are arrays are not MongooseArrays. we
54
+ // need to convert their elements as if they were MongooseArrays
55
+ // to handle populated arrays versus DocumentArrays properly.
56
+ if (utils.isMongooseObject(val)) {
57
+ val = val.toObject(opts);
58
+ } else if (Array.isArray(val)) {
59
+ val = this.toObject.call(val, opts);
60
+ } else if (val != null && Array.isArray(val.$each)) {
61
+ val.$each = this.toObject.call(val.$each, opts);
62
+ } else if (val != null && typeof val.valueOf === 'function') {
63
+ val = val.valueOf();
64
+ }
65
+
66
+ if (op === '$addToSet') {
67
+ val = { $each: val };
68
+ }
69
+
70
+ ret.push([op, val]);
71
+ }
72
+
73
+ return ret;
74
+ },
75
+
76
+ /*!
77
+ * ignore
78
+ */
79
+
80
+ $atomics() {
81
+ return this[arrayAtomicsSymbol];
82
+ },
83
+
84
+ /*!
85
+ * ignore
86
+ */
87
+
88
+ $parent() {
89
+ return this[arrayParentSymbol];
90
+ },
91
+
92
+ /*!
93
+ * ignore
94
+ */
95
+
96
+ $path() {
97
+ return this[arrayPathSymbol];
98
+ },
99
+
100
+ /**
101
+ * Atomically shifts the array at most one time per document `save()`.
102
+ *
103
+ * #### Note:
104
+ *
105
+ * _Calling this multiple times on an array before saving sends the same command as calling it once._
106
+ * _This update is implemented using the MongoDB [$pop](https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
107
+ *
108
+ * doc.array = [1,2,3];
109
+ *
110
+ * const shifted = doc.array.$shift();
111
+ * console.log(shifted); // 1
112
+ * console.log(doc.array); // [2,3]
113
+ *
114
+ * // no affect
115
+ * shifted = doc.array.$shift();
116
+ * console.log(doc.array); // [2,3]
117
+ *
118
+ * doc.save(function (err) {
119
+ * if (err) return handleError(err);
120
+ *
121
+ * // we saved, now $shift works again
122
+ * shifted = doc.array.$shift();
123
+ * console.log(shifted ); // 2
124
+ * console.log(doc.array); // [3]
125
+ * })
126
+ *
127
+ * @api public
128
+ * @memberOf MongooseArray
129
+ * @instance
130
+ * @method $shift
131
+ * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
132
+ */
133
+
134
+ $shift() {
135
+ this._registerAtomic('$pop', -1);
136
+ this._markModified();
137
+
138
+ // only allow shifting once
139
+ const __array = this.__array;
140
+ if (__array._shifted) {
141
+ return;
142
+ }
143
+ __array._shifted = true;
144
+
145
+ return [].shift.call(__array);
146
+ },
147
+
148
+ /**
149
+ * Pops the array atomically at most one time per document `save()`.
150
+ *
151
+ * #### NOTE:
152
+ *
153
+ * _Calling this multiple times on an array before saving sends the same command as calling it once._
154
+ * _This update is implemented using the MongoDB [$pop](https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
155
+ *
156
+ * doc.array = [1,2,3];
157
+ *
158
+ * const popped = doc.array.$pop();
159
+ * console.log(popped); // 3
160
+ * console.log(doc.array); // [1,2]
161
+ *
162
+ * // no affect
163
+ * popped = doc.array.$pop();
164
+ * console.log(doc.array); // [1,2]
165
+ *
166
+ * doc.save(function (err) {
167
+ * if (err) return handleError(err);
168
+ *
169
+ * // we saved, now $pop works again
170
+ * popped = doc.array.$pop();
171
+ * console.log(popped); // 2
172
+ * console.log(doc.array); // [1]
173
+ * })
174
+ *
175
+ * @api public
176
+ * @method $pop
177
+ * @memberOf MongooseArray
178
+ * @instance
179
+ * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
180
+ * @method $pop
181
+ * @memberOf MongooseArray
182
+ */
183
+
184
+ $pop() {
185
+ this._registerAtomic('$pop', 1);
186
+ this._markModified();
187
+
188
+ // only allow popping once
189
+ if (this._popped) {
190
+ return;
191
+ }
192
+ this._popped = true;
193
+
194
+ return [].pop.call(this);
195
+ },
196
+
197
+ /*!
198
+ * ignore
199
+ */
200
+
201
+ $schema() {
202
+ return this[arraySchemaSymbol];
203
+ },
204
+
205
+ /**
206
+ * Casts a member based on this arrays schema.
207
+ *
208
+ * @param {any} value
209
+ * @return value the casted value
210
+ * @method _cast
211
+ * @api private
212
+ * @memberOf MongooseArray
213
+ */
214
+
215
+ _cast(value) {
216
+ let populated = false;
217
+ let Model;
218
+
219
+ const parent = this[arrayParentSymbol];
220
+ if (parent) {
221
+ populated = parent.$populated(this[arrayPathSymbol], true);
222
+ }
223
+
224
+ if (populated && value !== null && value !== undefined) {
225
+ // cast to the populated Models schema
226
+ Model = populated.options[populateModelSymbol];
227
+
228
+ // only objects are permitted so we can safely assume that
229
+ // non-objects are to be interpreted as _id
230
+ if (Buffer.isBuffer(value) ||
231
+ isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
232
+ value = { _id: value };
233
+ }
234
+
235
+ // gh-2399
236
+ // we should cast model only when it's not a discriminator
237
+ const isDisc = value.schema && value.schema.discriminatorMapping &&
238
+ value.schema.discriminatorMapping.key !== undefined;
239
+ if (!isDisc) {
240
+ value = new Model(value);
241
+ }
242
+ return this[arraySchemaSymbol].caster.applySetters(value, parent, true);
243
+ }
244
+
245
+ return this[arraySchemaSymbol].caster.applySetters(value, parent, false);
246
+ },
247
+
248
+ /**
249
+ * Internal helper for .map()
250
+ *
251
+ * @api private
252
+ * @return {Number}
253
+ * @method _mapCast
254
+ * @memberOf MongooseArray
255
+ */
256
+
257
+ _mapCast(val, index) {
258
+ return this._cast(val, this.length + index);
259
+ },
260
+
261
+ /**
262
+ * Marks this array as modified.
263
+ *
264
+ * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
265
+ *
266
+ * @param {ArraySubdocument} subdoc the embedded doc that invoked this method on the Array
267
+ * @param {String} embeddedPath the path which changed in the subdoc
268
+ * @method _markModified
269
+ * @api private
270
+ * @memberOf MongooseArray
271
+ */
272
+
273
+ _markModified(elem) {
274
+ const parent = this[arrayParentSymbol];
275
+ let dirtyPath;
276
+
277
+ if (parent) {
278
+ dirtyPath = this[arrayPathSymbol];
279
+
280
+ if (arguments.length) {
281
+ dirtyPath = dirtyPath + '.' + elem;
282
+ }
283
+
284
+ if (dirtyPath != null && dirtyPath.endsWith('.$')) {
285
+ return this;
286
+ }
287
+
288
+ parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent);
289
+ }
290
+
291
+ return this;
292
+ },
293
+
294
+ /**
295
+ * Register an atomic operation with the parent.
296
+ *
297
+ * @param {Array} op operation
298
+ * @param {any} val
299
+ * @method _registerAtomic
300
+ * @api private
301
+ * @memberOf MongooseArray
302
+ */
303
+
304
+ _registerAtomic(op, val) {
305
+ if (this[slicedSymbol]) {
306
+ return;
307
+ }
308
+ if (op === '$set') {
309
+ // $set takes precedence over all other ops.
310
+ // mark entire array modified.
311
+ this[arrayAtomicsSymbol] = { $set: val };
312
+ cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]);
313
+ this._markModified();
314
+ return this;
315
+ }
316
+
317
+ const atomics = this[arrayAtomicsSymbol];
318
+
319
+ // reset pop/shift after save
320
+ if (op === '$pop' && !('$pop' in atomics)) {
321
+ const _this = this;
322
+ this[arrayParentSymbol].once('save', function() {
323
+ _this._popped = _this._shifted = null;
324
+ });
325
+ }
326
+
327
+ // check for impossible $atomic combos (Mongo denies more than one
328
+ // $atomic op on a single path
329
+ if (atomics.$set || Object.keys(atomics).length && !(op in atomics)) {
330
+ // a different op was previously registered.
331
+ // save the entire thing.
332
+ this[arrayAtomicsSymbol] = { $set: this };
333
+ return this;
334
+ }
335
+
336
+ let selector;
337
+
338
+ if (op === '$pullAll' || op === '$addToSet') {
339
+ atomics[op] || (atomics[op] = []);
340
+ atomics[op] = atomics[op].concat(val);
341
+ } else if (op === '$pullDocs') {
342
+ const pullOp = atomics['$pull'] || (atomics['$pull'] = {});
343
+ if (val[0] instanceof ArraySubdocument) {
344
+ selector = pullOp['$or'] || (pullOp['$or'] = []);
345
+ Array.prototype.push.apply(selector, val.map(v => {
346
+ return v.toObject({
347
+ transform: (doc, ret) => {
348
+ if (v == null || v.$__ == null) {
349
+ return ret;
350
+ }
351
+
352
+ Object.keys(v.$__.activePaths.getStatePaths('default')).forEach(path => {
353
+ mpath.unset(path, ret);
354
+
355
+ _minimizePath(ret, path);
356
+ });
357
+
358
+ return ret;
359
+ },
360
+ virtuals: false
361
+ });
362
+ }));
363
+ } else {
364
+ selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] });
365
+ selector['$in'] = selector['$in'].concat(val);
366
+ }
367
+ } else if (op === '$push') {
368
+ atomics.$push = atomics.$push || { $each: [] };
369
+ if (val != null && utils.hasUserDefinedProperty(val, '$each')) {
370
+ atomics.$push = val;
371
+ } else {
372
+ atomics.$push.$each = atomics.$push.$each.concat(val);
373
+ }
374
+ } else {
375
+ atomics[op] = val;
376
+ }
377
+
378
+ return this;
379
+ },
380
+
381
+ /**
382
+ * Adds values to the array if not already present.
383
+ *
384
+ * #### Example:
385
+ *
386
+ * console.log(doc.array) // [2,3,4]
387
+ * const added = doc.array.addToSet(4,5);
388
+ * console.log(doc.array) // [2,3,4,5]
389
+ * console.log(added) // [5]
390
+ *
391
+ * @param {...any} [args]
392
+ * @return {Array} the values that were added
393
+ * @memberOf MongooseArray
394
+ * @api public
395
+ * @method addToSet
396
+ */
397
+
398
+ addToSet() {
399
+ _checkManualPopulation(this, arguments);
400
+
401
+ let values = [].map.call(arguments, this._mapCast, this);
402
+ values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
403
+ const added = [];
404
+ let type = '';
405
+ if (values[0] instanceof ArraySubdocument) {
406
+ type = 'doc';
407
+ } else if (values[0] instanceof Date) {
408
+ type = 'date';
409
+ }
410
+
411
+ const rawValues = utils.isMongooseArray(values) ? values.__array : this;
412
+ const rawArray = utils.isMongooseArray(this) ? this.__array : this;
413
+
414
+ rawValues.forEach(function(v) {
415
+ let found;
416
+ const val = +v;
417
+ switch (type) {
418
+ case 'doc':
419
+ found = this.some(function(doc) {
420
+ return doc.equals(v);
421
+ });
422
+ break;
423
+ case 'date':
424
+ found = this.some(function(d) {
425
+ return +d === val;
426
+ });
427
+ break;
428
+ default:
429
+ found = ~this.indexOf(v);
430
+ }
431
+
432
+ if (!found) {
433
+ this._markModified();
434
+ rawArray.push(v);
435
+ this._registerAtomic('$addToSet', v);
436
+ [].push.call(added, v);
437
+ }
438
+ }, this);
439
+
440
+ return added;
441
+ },
442
+
443
+ /**
444
+ * Returns the number of pending atomic operations to send to the db for this array.
445
+ *
446
+ * @api private
447
+ * @return {Number}
448
+ * @method hasAtomics
449
+ * @memberOf MongooseArray
450
+ */
451
+
452
+ hasAtomics() {
453
+ if (!utils.isPOJO(this[arrayAtomicsSymbol])) {
454
+ return 0;
455
+ }
456
+
457
+ return Object.keys(this[arrayAtomicsSymbol]).length;
458
+ },
459
+
460
+ /**
461
+ * Return whether or not the `obj` is included in the array.
462
+ *
463
+ * @param {Object} obj the item to check
464
+ * @param {Number} fromIndex
465
+ * @return {Boolean}
466
+ * @api public
467
+ * @method includes
468
+ * @memberOf MongooseArray
469
+ */
470
+
471
+ includes(obj, fromIndex) {
472
+ const ret = this.indexOf(obj, fromIndex);
473
+ return ret !== -1;
474
+ },
475
+
476
+ /**
477
+ * Return the index of `obj` or `-1` if not found.
478
+ *
479
+ * @param {Object} obj the item to look for
480
+ * @param {Number} fromIndex
481
+ * @return {Number}
482
+ * @api public
483
+ * @method indexOf
484
+ * @memberOf MongooseArray
485
+ */
486
+
487
+ indexOf(obj, fromIndex) {
488
+ if (isBsonType(obj, 'ObjectID')) {
489
+ obj = obj.toString();
490
+ }
491
+
492
+ fromIndex = fromIndex == null ? 0 : fromIndex;
493
+ const len = this.length;
494
+ for (let i = fromIndex; i < len; ++i) {
495
+ if (obj == this[i]) {
496
+ return i;
497
+ }
498
+ }
499
+ return -1;
500
+ },
501
+
502
+ /**
503
+ * Helper for console.log
504
+ *
505
+ * @api public
506
+ * @method inspect
507
+ * @memberOf MongooseArray
508
+ */
509
+
510
+ inspect() {
511
+ return JSON.stringify(this);
512
+ },
513
+
514
+ /**
515
+ * Pushes items to the array non-atomically.
516
+ *
517
+ * #### Note:
518
+ *
519
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
520
+ *
521
+ * @param {...any} [args]
522
+ * @api public
523
+ * @method nonAtomicPush
524
+ * @memberOf MongooseArray
525
+ */
526
+
527
+ nonAtomicPush() {
528
+ const values = [].map.call(arguments, this._mapCast, this);
529
+ this._markModified();
530
+ const ret = [].push.apply(this, values);
531
+ this._registerAtomic('$set', this);
532
+ return ret;
533
+ },
534
+
535
+ /**
536
+ * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
537
+ *
538
+ * #### Note:
539
+ *
540
+ * _marks the entire array as modified which will pass the entire thing to $set potentially overwriting any changes that happen between when you retrieved the object and when you save it._
541
+ *
542
+ * @see MongooseArray#$pop #types_array_MongooseArray-%24pop
543
+ * @api public
544
+ * @method pop
545
+ * @memberOf MongooseArray
546
+ */
547
+
548
+ pop() {
549
+ this._markModified();
550
+ const ret = [].pop.call(this);
551
+ this._registerAtomic('$set', this);
552
+ return ret;
553
+ },
554
+
555
+ /**
556
+ * Pulls items from the array atomically. Equality is determined by casting
557
+ * the provided value to an embedded document and comparing using
558
+ * [the `Document.equals()` function.](/docs/api/document.html#document_Document-equals)
559
+ *
560
+ * #### Example:
561
+ *
562
+ * doc.array.pull(ObjectId)
563
+ * doc.array.pull({ _id: 'someId' })
564
+ * doc.array.pull(36)
565
+ * doc.array.pull('tag 1', 'tag 2')
566
+ *
567
+ * To remove a document from a subdocument array we may pass an object with a matching `_id`.
568
+ *
569
+ * doc.subdocs.push({ _id: 4815162342 })
570
+ * doc.subdocs.pull({ _id: 4815162342 }) // removed
571
+ *
572
+ * Or we may passing the _id directly and let mongoose take care of it.
573
+ *
574
+ * doc.subdocs.push({ _id: 4815162342 })
575
+ * doc.subdocs.pull(4815162342); // works
576
+ *
577
+ * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.
578
+ *
579
+ * @param {...any} [args]
580
+ * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
581
+ * @api public
582
+ * @method pull
583
+ * @memberOf MongooseArray
584
+ */
585
+
586
+ pull() {
587
+ const values = [].map.call(arguments, this._cast, this);
588
+ const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]);
589
+ let i = cur.length;
590
+ let mem;
591
+ this._markModified();
592
+
593
+ while (i--) {
594
+ mem = cur[i];
595
+ if (mem instanceof Document) {
596
+ const some = values.some(function(v) {
597
+ return mem.equals(v);
598
+ });
599
+ if (some) {
600
+ [].splice.call(cur, i, 1);
601
+ }
602
+ } else if (~cur.indexOf.call(values, mem)) {
603
+ [].splice.call(cur, i, 1);
604
+ }
605
+ }
606
+
607
+ if (values[0] instanceof ArraySubdocument) {
608
+ this._registerAtomic('$pullDocs', values.map(function(v) {
609
+ const _id = v.$__getValue('_id');
610
+ if (_id === undefined || v.$isDefault('_id')) {
611
+ return v;
612
+ }
613
+ return _id;
614
+ }));
615
+ } else {
616
+ this._registerAtomic('$pullAll', values);
617
+ }
618
+
619
+
620
+ // Might have modified child paths and then pulled, like
621
+ // `doc.children[1].name = 'test';` followed by
622
+ // `doc.children.remove(doc.children[0]);`. In this case we fall back
623
+ // to a `$set` on the whole array. See #3511
624
+ if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) {
625
+ this._registerAtomic('$set', this);
626
+ }
627
+
628
+ return this;
629
+ },
630
+
631
+ /**
632
+ * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
633
+ *
634
+ * #### Example:
635
+ *
636
+ * const schema = Schema({ nums: [Number] });
637
+ * const Model = mongoose.model('Test', schema);
638
+ *
639
+ * const doc = await Model.create({ nums: [3, 4] });
640
+ * doc.nums.push(5); // Add 5 to the end of the array
641
+ * await doc.save();
642
+ *
643
+ * // You can also pass an object with `$each` as the
644
+ * // first parameter to use MongoDB's `$position`
645
+ * doc.nums.push({
646
+ * $each: [1, 2],
647
+ * $position: 0
648
+ * });
649
+ * doc.nums; // [1, 2, 3, 4, 5]
650
+ *
651
+ * @param {...Object} [args]
652
+ * @api public
653
+ * @method push
654
+ * @memberOf MongooseArray
655
+ */
656
+
657
+ push() {
658
+ let values = arguments;
659
+ let atomic = values;
660
+ const isOverwrite = values[0] != null &&
661
+ utils.hasUserDefinedProperty(values[0], '$each');
662
+ const arr = utils.isMongooseArray(this) ? this.__array : this;
663
+ if (isOverwrite) {
664
+ atomic = values[0];
665
+ values = values[0].$each;
666
+ }
667
+
668
+ if (this[arraySchemaSymbol] == null) {
669
+ return _basePush.apply(this, values);
670
+ }
671
+
672
+ _checkManualPopulation(this, values);
673
+
674
+ const parent = this[arrayParentSymbol];
675
+ values = [].map.call(values, this._mapCast, this);
676
+ values = this[arraySchemaSymbol].applySetters(values, parent, undefined,
677
+ undefined, { skipDocumentArrayCast: true });
678
+ let ret;
679
+ const atomics = this[arrayAtomicsSymbol];
680
+ this._markModified();
681
+ if (isOverwrite) {
682
+ atomic.$each = values;
683
+
684
+ if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 &&
685
+ atomics.$push.$position != atomic.$position) {
686
+ if (atomic.$position != null) {
687
+ [].splice.apply(arr, [atomic.$position, 0].concat(values));
688
+ ret = arr.length;
689
+ } else {
690
+ ret = [].push.apply(arr, values);
691
+ }
692
+
693
+ this._registerAtomic('$set', this);
694
+ } else if (atomic.$position != null) {
695
+ [].splice.apply(arr, [atomic.$position, 0].concat(values));
696
+ ret = this.length;
697
+ } else {
698
+ ret = [].push.apply(arr, values);
699
+ }
700
+ } else {
701
+ atomic = values;
702
+ ret = [].push.apply(arr, values);
703
+ }
704
+
705
+ this._registerAtomic('$push', atomic);
706
+ return ret;
707
+ },
708
+
709
+ /**
710
+ * Alias of [pull](#mongoosearray_MongooseArray-pull)
711
+ *
712
+ * @see MongooseArray#pull #types_array_MongooseArray-pull
713
+ * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
714
+ * @api public
715
+ * @memberOf MongooseArray
716
+ * @instance
717
+ * @method remove
718
+ */
719
+
720
+ remove() {
721
+ return this.pull.apply(this, arguments);
722
+ },
723
+
724
+ /**
725
+ * Sets the casted `val` at index `i` and marks the array modified.
726
+ *
727
+ * #### Example:
728
+ *
729
+ * // given documents based on the following
730
+ * const Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
731
+ *
732
+ * const doc = new Doc({ array: [2,3,4] })
733
+ *
734
+ * console.log(doc.array) // [2,3,4]
735
+ *
736
+ * doc.array.set(1,"5");
737
+ * console.log(doc.array); // [2,5,4] // properly cast to number
738
+ * doc.save() // the change is saved
739
+ *
740
+ * // VS not using array#set
741
+ * doc.array[1] = "5";
742
+ * console.log(doc.array); // [2,"5",4] // no casting
743
+ * doc.save() // change is not saved
744
+ *
745
+ * @return {Array} this
746
+ * @api public
747
+ * @method set
748
+ * @memberOf MongooseArray
749
+ */
750
+
751
+ set(i, val, skipModified) {
752
+ const arr = this.__array;
753
+ if (skipModified) {
754
+ arr[i] = val;
755
+ return this;
756
+ }
757
+ const value = methods._cast.call(this, val, i);
758
+ methods._markModified.call(this, i);
759
+ arr[i] = value;
760
+ return this;
761
+ },
762
+
763
+ /**
764
+ * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
765
+ *
766
+ * #### Example:
767
+ *
768
+ * doc.array = [2,3];
769
+ * const res = doc.array.shift();
770
+ * console.log(res) // 2
771
+ * console.log(doc.array) // [3]
772
+ *
773
+ * #### Note:
774
+ *
775
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
776
+ *
777
+ * @api public
778
+ * @method shift
779
+ * @memberOf MongooseArray
780
+ */
781
+
782
+ shift() {
783
+ const arr = utils.isMongooseArray(this) ? this.__array : this;
784
+ this._markModified();
785
+ const ret = [].shift.call(arr);
786
+ this._registerAtomic('$set', this);
787
+ return ret;
788
+ },
789
+
790
+ /**
791
+ * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
792
+ *
793
+ * #### Note:
794
+ *
795
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
796
+ *
797
+ * @api public
798
+ * @method sort
799
+ * @memberOf MongooseArray
800
+ * @see https://masteringjs.io/tutorials/fundamentals/array-sort
801
+ */
802
+
803
+ sort() {
804
+ const arr = utils.isMongooseArray(this) ? this.__array : this;
805
+ const ret = [].sort.apply(arr, arguments);
806
+ this._registerAtomic('$set', this);
807
+ return ret;
808
+ },
809
+
810
+ /**
811
+ * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
812
+ *
813
+ * #### Note:
814
+ *
815
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
816
+ *
817
+ * @api public
818
+ * @method splice
819
+ * @memberOf MongooseArray
820
+ * @see https://masteringjs.io/tutorials/fundamentals/array-splice
821
+ */
822
+
823
+ splice() {
824
+ let ret;
825
+ const arr = utils.isMongooseArray(this) ? this.__array : this;
826
+
827
+ this._markModified();
828
+ _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2));
829
+
830
+ if (arguments.length) {
831
+ let vals;
832
+ if (this[arraySchemaSymbol] == null) {
833
+ vals = arguments;
834
+ } else {
835
+ vals = [];
836
+ for (let i = 0; i < arguments.length; ++i) {
837
+ vals[i] = i < 2 ?
838
+ arguments[i] :
839
+ this._cast(arguments[i], arguments[0] + (i - 2));
840
+ }
841
+ }
842
+
843
+ ret = [].splice.apply(arr, vals);
844
+ this._registerAtomic('$set', this);
845
+ }
846
+
847
+ return ret;
848
+ },
849
+
850
+ /*!
851
+ * ignore
852
+ */
853
+
854
+ toBSON() {
855
+ return this.toObject(internalToObjectOptions);
856
+ },
857
+
858
+ /**
859
+ * Returns a native js Array.
860
+ *
861
+ * @param {Object} options
862
+ * @return {Array}
863
+ * @api public
864
+ * @method toObject
865
+ * @memberOf MongooseArray
866
+ */
867
+
868
+ toObject(options) {
869
+ const arr = utils.isMongooseArray(this) ? this.__array : this;
870
+ if (options && options.depopulate) {
871
+ options = utils.clone(options);
872
+ options._isNested = true;
873
+ // Ensure return value is a vanilla array, because in Node.js 6+ `map()`
874
+ // is smart enough to use the inherited array's constructor.
875
+ return [].concat(arr).map(function(doc) {
876
+ return doc instanceof Document
877
+ ? doc.toObject(options)
878
+ : doc;
879
+ });
880
+ }
881
+
882
+ return [].concat(arr);
883
+ },
884
+
885
+ $toObject() {
886
+ return this.constructor.prototype.toObject.apply(this, arguments);
887
+ },
888
+ /**
889
+ * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
890
+ *
891
+ * #### Note:
892
+ *
893
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._
894
+ *
895
+ * @api public
896
+ * @method unshift
897
+ * @memberOf MongooseArray
898
+ */
899
+
900
+ unshift() {
901
+ _checkManualPopulation(this, arguments);
902
+
903
+ let values;
904
+ if (this[arraySchemaSymbol] == null) {
905
+ values = arguments;
906
+ } else {
907
+ values = [].map.call(arguments, this._cast, this);
908
+ values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
909
+ }
910
+
911
+ const arr = utils.isMongooseArray(this) ? this.__array : this;
912
+ this._markModified();
913
+ [].unshift.apply(arr, values);
914
+ this._registerAtomic('$set', this);
915
+ return this.length;
916
+ }
917
+ };
918
+
919
+ /*!
920
+ * ignore
921
+ */
922
+
923
+ function _isAllSubdocs(docs, ref) {
924
+ if (!ref) {
925
+ return false;
926
+ }
927
+
928
+ for (const arg of docs) {
929
+ if (arg == null) {
930
+ return false;
931
+ }
932
+ const model = arg.constructor;
933
+ if (!(arg instanceof Document) ||
934
+ (model.modelName !== ref && model.baseModelName !== ref)) {
935
+ return false;
936
+ }
937
+ }
938
+
939
+ return true;
940
+ }
941
+
942
+ /*!
943
+ * Minimize _just_ empty objects along the path chain specified
944
+ * by `parts`, ignoring all other paths. Useful in cases where
945
+ * you want to minimize after unsetting a path.
946
+ *
947
+ * #### Example:
948
+ *
949
+ * const obj = { foo: { bar: { baz: {} } }, a: {} };
950
+ * _minimizePath(obj, 'foo.bar.baz');
951
+ * obj; // { a: {} }
952
+ */
953
+
954
+ function _minimizePath(obj, parts, i) {
955
+ if (typeof parts === 'string') {
956
+ if (parts.indexOf('.') === -1) {
957
+ return;
958
+ }
959
+
960
+ parts = mpath.stringToParts(parts);
961
+ }
962
+ i = i || 0;
963
+ if (i >= parts.length) {
964
+ return;
965
+ }
966
+ if (obj == null || typeof obj !== 'object') {
967
+ return;
968
+ }
969
+
970
+ _minimizePath(obj[parts[0]], parts, i + 1);
971
+ if (obj[parts[0]] != null && typeof obj[parts[0]] === 'object' && Object.keys(obj[parts[0]]).length === 0) {
972
+ delete obj[parts[0]];
973
+ }
974
+ }
975
+
976
+ /*!
977
+ * ignore
978
+ */
979
+
980
+ function _checkManualPopulation(arr, docs) {
981
+ const ref = arr == null ?
982
+ null :
983
+ arr[arraySchemaSymbol] && arr[arraySchemaSymbol].caster && arr[arraySchemaSymbol].caster.options && arr[arraySchemaSymbol].caster.options.ref || null;
984
+ if (arr.length === 0 &&
985
+ docs.length !== 0) {
986
+ if (_isAllSubdocs(docs, ref)) {
987
+ arr[arrayParentSymbol].$populated(arr[arrayPathSymbol], [], {
988
+ [populateModelSymbol]: docs[0].constructor
989
+ });
990
+ }
991
+ }
992
+ }
993
+
994
+ const returnVanillaArrayMethods = [
995
+ 'filter',
996
+ 'flat',
997
+ 'flatMap',
998
+ 'map',
999
+ 'slice'
1000
+ ];
1001
+ for (const method of returnVanillaArrayMethods) {
1002
+ if (Array.prototype[method] == null) {
1003
+ continue;
1004
+ }
1005
+
1006
+ methods[method] = function() {
1007
+ const _arr = utils.isMongooseArray(this) ? this.__array : this;
1008
+ const arr = [].concat(_arr);
1009
+
1010
+ return arr[method].apply(arr, arguments);
1011
+ };
1012
+ }
1013
+
1014
+ module.exports = methods;