@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,756 @@
1
+ 'use strict';
2
+
3
+ const MongooseError = require('../../error/index');
4
+ const SkipPopulateValue = require('./SkipPopulateValue');
5
+ const get = require('../get');
6
+ const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
7
+ const getConstructorName = require('../getConstructorName');
8
+ const getSchemaTypes = require('./getSchemaTypes');
9
+ const getVirtual = require('./getVirtual');
10
+ const lookupLocalFields = require('./lookupLocalFields');
11
+ const mpath = require('mpath');
12
+ const modelNamesFromRefPath = require('./modelNamesFromRefPath');
13
+ const utils = require('../../utils');
14
+
15
+ const modelSymbol = require('../symbols').modelSymbol;
16
+ const populateModelSymbol = require('../symbols').populateModelSymbol;
17
+ const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
18
+ const StrictPopulate = require('../../error/strictPopulate');
19
+
20
+ module.exports = function getModelsMapForPopulate(model, docs, options) {
21
+ let doc;
22
+ const len = docs.length;
23
+ const map = [];
24
+ const modelNameFromQuery = options.model && options.model.modelName || options.model;
25
+ let schema;
26
+ let refPath;
27
+ let modelNames;
28
+ const available = {};
29
+
30
+ const modelSchema = model.schema;
31
+
32
+ // Populating a nested path should always be a no-op re: #9073.
33
+ // People shouldn't do this, but apparently they do.
34
+ if (options._localModel != null && options._localModel.schema.nested[options.path]) {
35
+ return [];
36
+ }
37
+
38
+ const _virtualRes = getVirtual(model.schema, options.path);
39
+ const virtual = _virtualRes == null ? null : _virtualRes.virtual;
40
+ if (virtual != null) {
41
+ return _virtualPopulate(model, docs, options, _virtualRes);
42
+ }
43
+
44
+ let allSchemaTypes = getSchemaTypes(model, modelSchema, null, options.path);
45
+ allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null);
46
+
47
+ if (allSchemaTypes.length === 0 && options.strictPopulate !== false && options._localModel != null) {
48
+ return new StrictPopulate(options._fullPath || options.path);
49
+ }
50
+
51
+ for (let i = 0; i < len; i++) {
52
+ doc = docs[i];
53
+ let justOne = null;
54
+
55
+ const docSchema = doc != null && doc.$__ != null ? doc.$__schema : modelSchema;
56
+ schema = getSchemaTypes(model, docSchema, doc, options.path);
57
+
58
+ // Special case: populating a path that's a DocumentArray unless
59
+ // there's an explicit `ref` or `refPath` re: gh-8946
60
+ if (schema != null &&
61
+ schema.$isMongooseDocumentArray &&
62
+ schema.options.ref == null &&
63
+ schema.options.refPath == null) {
64
+ continue;
65
+ }
66
+ const isUnderneathDocArray = schema && schema.$isUnderneathDocArray;
67
+ if (isUnderneathDocArray && get(options, 'options.sort') != null) {
68
+ return new MongooseError('Cannot populate with `sort` on path ' + options.path +
69
+ ' because it is a subproperty of a document array');
70
+ }
71
+
72
+ modelNames = null;
73
+ let isRefPath = false;
74
+ let normalizedRefPath = null;
75
+ let schemaOptions = null;
76
+ let modelNamesInOrder = null;
77
+
78
+ if (schema != null && schema.instance === 'Embedded') {
79
+ if (schema.options.ref) {
80
+ const data = {
81
+ localField: options.path + '._id',
82
+ foreignField: '_id',
83
+ justOne: true
84
+ };
85
+ const res = _getModelNames(doc, schema, modelNameFromQuery, model);
86
+
87
+ const unpopulatedValue = mpath.get(options.path, doc);
88
+ const id = mpath.get('_id', unpopulatedValue);
89
+ addModelNamesToMap(model, map, available, res.modelNames, options, data, id, doc, schemaOptions, unpopulatedValue);
90
+ }
91
+ // No-op if no `ref` set. See gh-11538
92
+ continue;
93
+ }
94
+
95
+ if (Array.isArray(schema)) {
96
+ const schemasArray = schema;
97
+ for (const _schema of schemasArray) {
98
+ let _modelNames;
99
+ let res;
100
+ try {
101
+ res = _getModelNames(doc, _schema, modelNameFromQuery, model);
102
+ _modelNames = res.modelNames;
103
+ isRefPath = isRefPath || res.isRefPath;
104
+ normalizedRefPath = normalizedRefPath || res.refPath;
105
+ justOne = res.justOne;
106
+ } catch (error) {
107
+ return error;
108
+ }
109
+
110
+ if (isRefPath && !res.isRefPath) {
111
+ continue;
112
+ }
113
+ if (!_modelNames) {
114
+ continue;
115
+ }
116
+ modelNames = modelNames || [];
117
+ for (const modelName of _modelNames) {
118
+ if (modelNames.indexOf(modelName) === -1) {
119
+ modelNames.push(modelName);
120
+ }
121
+ }
122
+ }
123
+ } else {
124
+ try {
125
+ const res = _getModelNames(doc, schema, modelNameFromQuery, model);
126
+ modelNames = res.modelNames;
127
+ isRefPath = res.isRefPath;
128
+ normalizedRefPath = normalizedRefPath || res.refPath;
129
+ justOne = res.justOne;
130
+ schemaOptions = get(schema, 'options.populate', null);
131
+ // Dedupe, because `refPath` can return duplicates of the same model name,
132
+ // and that causes perf issues.
133
+ if (isRefPath) {
134
+ modelNamesInOrder = modelNames;
135
+ modelNames = Array.from(new Set(modelNames));
136
+ }
137
+ } catch (error) {
138
+ return error;
139
+ }
140
+
141
+ if (!modelNames) {
142
+ continue;
143
+ }
144
+ }
145
+
146
+ const data = {};
147
+ const localField = options.path;
148
+ const foreignField = '_id';
149
+
150
+ // `justOne = null` means we don't know from the schema whether the end
151
+ // result should be an array or a single doc. This can result from
152
+ // populating a POJO using `Model.populate()`
153
+ if ('justOne' in options && options.justOne !== void 0) {
154
+ justOne = options.justOne;
155
+ } else if (schema && !schema[schemaMixedSymbol]) {
156
+ // Skip Mixed types because we explicitly don't do casting on those.
157
+ if (options.path.endsWith('.' + schema.path) || options.path === schema.path) {
158
+ justOne = Array.isArray(schema) ?
159
+ schema.every(schema => !schema.$isMongooseArray) :
160
+ !schema.$isMongooseArray;
161
+ }
162
+ }
163
+
164
+ if (!modelNames) {
165
+ continue;
166
+ }
167
+
168
+ data.isVirtual = false;
169
+ data.justOne = justOne;
170
+ data.localField = localField;
171
+ data.foreignField = foreignField;
172
+
173
+ // Get local fields
174
+ const ret = _getLocalFieldValues(doc, localField, model, options, null, schema);
175
+
176
+ const id = String(utils.getValue(foreignField, doc));
177
+ options._docs[id] = Array.isArray(ret) ? ret.slice() : ret;
178
+
179
+ let match = get(options, 'match', null);
180
+
181
+ const hasMatchFunction = typeof match === 'function';
182
+ if (hasMatchFunction) {
183
+ match = match.call(doc, doc);
184
+ }
185
+ throwOn$where(match);
186
+ data.match = match;
187
+ data.hasMatchFunction = hasMatchFunction;
188
+ data.isRefPath = isRefPath;
189
+ data.modelNamesInOrder = modelNamesInOrder;
190
+
191
+ if (isRefPath) {
192
+ const embeddedDiscriminatorModelNames = _findRefPathForDiscriminators(doc,
193
+ modelSchema, data, options, normalizedRefPath, ret);
194
+
195
+ modelNames = embeddedDiscriminatorModelNames || modelNames;
196
+ }
197
+
198
+ try {
199
+ addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions);
200
+ } catch (err) {
201
+ return err;
202
+ }
203
+ }
204
+ return map;
205
+
206
+ function _getModelNames(doc, schema, modelNameFromQuery, model) {
207
+ let modelNames;
208
+ let isRefPath = false;
209
+ let justOne = null;
210
+
211
+ const originalSchema = schema;
212
+ if (schema && schema.instance === 'Array') {
213
+ schema = schema.caster;
214
+ }
215
+ if (schema && schema.$isSchemaMap) {
216
+ schema = schema.$__schemaType;
217
+ }
218
+
219
+ const ref = schema && schema.options && schema.options.ref;
220
+ refPath = schema && schema.options && schema.options.refPath;
221
+ if (schema != null &&
222
+ schema[schemaMixedSymbol] &&
223
+ !ref &&
224
+ !refPath &&
225
+ !modelNameFromQuery) {
226
+ return { modelNames: null };
227
+ }
228
+
229
+ if (modelNameFromQuery) {
230
+ modelNames = [modelNameFromQuery]; // query options
231
+ } else if (refPath != null) {
232
+ if (typeof refPath === 'function') {
233
+ const subdocPath = options.path.slice(0, options.path.length - schema.path.length - 1);
234
+ const vals = mpath.get(subdocPath, doc, lookupLocalFields);
235
+ const subdocsBeingPopulated = Array.isArray(vals) ?
236
+ utils.array.flatten(vals) :
237
+ (vals ? [vals] : []);
238
+
239
+ modelNames = new Set();
240
+ for (const subdoc of subdocsBeingPopulated) {
241
+ refPath = refPath.call(subdoc, subdoc, options.path);
242
+ modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection).
243
+ forEach(name => modelNames.add(name));
244
+ }
245
+ modelNames = Array.from(modelNames);
246
+ } else {
247
+ modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection);
248
+ }
249
+
250
+ isRefPath = true;
251
+ } else {
252
+ let ref;
253
+ let refPath;
254
+ let schemaForCurrentDoc;
255
+ let discriminatorValue;
256
+ let modelForCurrentDoc = model;
257
+ const discriminatorKey = model.schema.options.discriminatorKey;
258
+
259
+ if (!schema && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc))) {
260
+ // `modelNameForFind` is the discriminator value, so we might need
261
+ // find the discriminated model name
262
+ const discriminatorModel = getDiscriminatorByValue(model.discriminators, discriminatorValue) || model;
263
+ if (discriminatorModel != null) {
264
+ modelForCurrentDoc = discriminatorModel;
265
+ } else {
266
+ try {
267
+ modelForCurrentDoc = _getModelFromConn(model.db, discriminatorValue);
268
+ } catch (error) {
269
+ return error;
270
+ }
271
+ }
272
+
273
+ schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path);
274
+
275
+ if (schemaForCurrentDoc && schemaForCurrentDoc.caster) {
276
+ schemaForCurrentDoc = schemaForCurrentDoc.caster;
277
+ }
278
+ } else {
279
+ schemaForCurrentDoc = schema;
280
+ }
281
+
282
+ if (originalSchema && originalSchema.path.endsWith('.$*')) {
283
+ justOne = !originalSchema.$isMongooseArray && !originalSchema._arrayPath;
284
+ } else if (schemaForCurrentDoc != null) {
285
+ justOne = !schemaForCurrentDoc.$isMongooseArray && !schemaForCurrentDoc._arrayPath;
286
+ }
287
+
288
+ if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) {
289
+ if (schemaForCurrentDoc != null &&
290
+ typeof ref === 'function' &&
291
+ options.path.endsWith('.' + schemaForCurrentDoc.path)) {
292
+ // Ensure correct context for ref functions: subdoc, not top-level doc. See gh-8469
293
+ modelNames = new Set();
294
+
295
+ const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1);
296
+ const vals = mpath.get(subdocPath, doc, lookupLocalFields);
297
+ const subdocsBeingPopulated = Array.isArray(vals) ?
298
+ utils.array.flatten(vals) :
299
+ (vals ? [vals] : []);
300
+ for (const subdoc of subdocsBeingPopulated) {
301
+ modelNames.add(handleRefFunction(ref, subdoc));
302
+ }
303
+
304
+ if (subdocsBeingPopulated.length === 0) {
305
+ modelNames = [handleRefFunction(ref, doc)];
306
+ } else {
307
+ modelNames = Array.from(modelNames);
308
+ }
309
+ } else {
310
+ ref = handleRefFunction(ref, doc);
311
+ modelNames = [ref];
312
+ }
313
+ } else if ((schemaForCurrentDoc = get(schema, 'options.refPath')) != null) {
314
+ isRefPath = true;
315
+ if (typeof refPath === 'function') {
316
+ const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1);
317
+ const vals = mpath.get(subdocPath, doc, lookupLocalFields);
318
+ const subdocsBeingPopulated = Array.isArray(vals) ?
319
+ utils.array.flatten(vals) :
320
+ (vals ? [vals] : []);
321
+
322
+ modelNames = new Set();
323
+ for (const subdoc of subdocsBeingPopulated) {
324
+ refPath = refPath.call(subdoc, subdoc, options.path);
325
+ modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection).
326
+ forEach(name => modelNames.add(name));
327
+ }
328
+ modelNames = Array.from(modelNames);
329
+ } else {
330
+ modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection);
331
+ }
332
+ }
333
+ }
334
+
335
+ if (!modelNames) {
336
+ // `Model.populate()` on a POJO with no known local model. Default to using the `Model`
337
+ if (options._localModel == null) {
338
+ modelNames = [model.modelName];
339
+ } else {
340
+ return { modelNames: modelNames, justOne: justOne, isRefPath: isRefPath, refPath: refPath };
341
+ }
342
+ }
343
+
344
+ if (!Array.isArray(modelNames)) {
345
+ modelNames = [modelNames];
346
+ }
347
+
348
+ return { modelNames: modelNames, justOne: justOne, isRefPath: isRefPath, refPath: refPath };
349
+ }
350
+ };
351
+
352
+ /*!
353
+ * ignore
354
+ */
355
+
356
+ function _virtualPopulate(model, docs, options, _virtualRes) {
357
+ const map = [];
358
+ const available = {};
359
+ const virtual = _virtualRes.virtual;
360
+
361
+ for (const doc of docs) {
362
+ let modelNames = null;
363
+ const data = {};
364
+
365
+ // localField and foreignField
366
+ let localField;
367
+ const virtualPrefix = _virtualRes.nestedSchemaPath ?
368
+ _virtualRes.nestedSchemaPath + '.' : '';
369
+ if (typeof options.localField === 'string') {
370
+ localField = options.localField;
371
+ } else if (typeof virtual.options.localField === 'function') {
372
+ localField = virtualPrefix + virtual.options.localField.call(doc, doc);
373
+ } else if (Array.isArray(virtual.options.localField)) {
374
+ localField = virtual.options.localField.map(field => virtualPrefix + field);
375
+ } else {
376
+ localField = virtualPrefix + virtual.options.localField;
377
+ }
378
+ data.count = virtual.options.count;
379
+
380
+ if (virtual.options.skip != null && !options.hasOwnProperty('skip')) {
381
+ options.skip = virtual.options.skip;
382
+ }
383
+ if (virtual.options.limit != null && !options.hasOwnProperty('limit')) {
384
+ options.limit = virtual.options.limit;
385
+ }
386
+ if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty('perDocumentLimit')) {
387
+ options.perDocumentLimit = virtual.options.perDocumentLimit;
388
+ }
389
+ let foreignField = virtual.options.foreignField;
390
+
391
+ if (!localField || !foreignField) {
392
+ return new MongooseError('If you are populating a virtual, you must set the ' +
393
+ 'localField and foreignField options');
394
+ }
395
+
396
+ if (typeof localField === 'function') {
397
+ localField = localField.call(doc, doc);
398
+ }
399
+ if (typeof foreignField === 'function') {
400
+ foreignField = foreignField.call(doc, doc);
401
+ }
402
+
403
+ data.isRefPath = false;
404
+
405
+ // `justOne = null` means we don't know from the schema whether the end
406
+ // result should be an array or a single doc. This can result from
407
+ // populating a POJO using `Model.populate()`
408
+ let justOne = null;
409
+ if ('justOne' in options && options.justOne !== void 0) {
410
+ justOne = options.justOne;
411
+ }
412
+
413
+ if (virtual.options.refPath) {
414
+ modelNames =
415
+ modelNamesFromRefPath(virtual.options.refPath, doc, options.path);
416
+ justOne = !!virtual.options.justOne;
417
+ data.isRefPath = true;
418
+ } else if (virtual.options.ref) {
419
+ let normalizedRef;
420
+ if (typeof virtual.options.ref === 'function' && !virtual.options.ref[modelSymbol]) {
421
+ normalizedRef = virtual.options.ref.call(doc, doc);
422
+ } else {
423
+ normalizedRef = virtual.options.ref;
424
+ }
425
+ justOne = !!virtual.options.justOne;
426
+ // When referencing nested arrays, the ref should be an Array
427
+ // of modelNames.
428
+ if (Array.isArray(normalizedRef)) {
429
+ modelNames = normalizedRef;
430
+ } else {
431
+ modelNames = [normalizedRef];
432
+ }
433
+ }
434
+
435
+ data.isVirtual = true;
436
+ data.virtual = virtual;
437
+ data.justOne = justOne;
438
+
439
+ // `match`
440
+ let match = get(options, 'match', null) ||
441
+ get(data, 'virtual.options.match', null) ||
442
+ get(data, 'virtual.options.options.match', null);
443
+
444
+ let hasMatchFunction = typeof match === 'function';
445
+ if (hasMatchFunction) {
446
+ match = match.call(doc, doc);
447
+ }
448
+
449
+ if (Array.isArray(localField) && Array.isArray(foreignField) && localField.length === foreignField.length) {
450
+ match = Object.assign({}, match);
451
+ for (let i = 1; i < localField.length; ++i) {
452
+ match[foreignField[i]] = convertTo_id(mpath.get(localField[i], doc, lookupLocalFields), model.schema);
453
+ hasMatchFunction = true;
454
+ }
455
+
456
+ localField = localField[0];
457
+ foreignField = foreignField[0];
458
+ }
459
+ data.localField = localField;
460
+ data.foreignField = foreignField;
461
+ data.match = match;
462
+ data.hasMatchFunction = hasMatchFunction;
463
+
464
+ throwOn$where(match);
465
+
466
+ // Get local fields
467
+ const ret = _getLocalFieldValues(doc, localField, model, options, virtual);
468
+
469
+ try {
470
+ addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc);
471
+ } catch (err) {
472
+ return err;
473
+ }
474
+ }
475
+
476
+ return map;
477
+ }
478
+
479
+ /*!
480
+ * ignore
481
+ */
482
+
483
+ function addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions, unpopulatedValue) {
484
+ // `PopulateOptions#connection`: if the model is passed as a string, the
485
+ // connection matters because different connections have different models.
486
+ const connection = options.connection != null ? options.connection : model.db;
487
+
488
+ unpopulatedValue = unpopulatedValue === void 0 ? ret : unpopulatedValue;
489
+ if (Array.isArray(unpopulatedValue)) {
490
+ unpopulatedValue = utils.cloneArrays(unpopulatedValue);
491
+ }
492
+
493
+ if (modelNames == null) {
494
+ return;
495
+ }
496
+
497
+ let k = modelNames.length;
498
+ while (k--) {
499
+ const modelName = modelNames[k];
500
+ if (modelName == null) {
501
+ continue;
502
+ }
503
+
504
+ let Model;
505
+ if (options.model && options.model[modelSymbol]) {
506
+ Model = options.model;
507
+ } else if (modelName[modelSymbol]) {
508
+ Model = modelName;
509
+ } else {
510
+ try {
511
+ Model = _getModelFromConn(connection, modelName);
512
+ } catch (err) {
513
+ if (ret !== void 0) {
514
+ throw err;
515
+ }
516
+ Model = null;
517
+ }
518
+ }
519
+
520
+ let ids = ret;
521
+ const flat = Array.isArray(ret) ? utils.array.flatten(ret) : [];
522
+
523
+ const modelNamesForRefPath = data.modelNamesInOrder ? data.modelNamesInOrder : modelNames;
524
+ if (data.isRefPath && Array.isArray(ret) && flat.length === modelNamesForRefPath.length) {
525
+ ids = flat.filter((val, i) => modelNamesForRefPath[i] === modelName);
526
+ }
527
+
528
+ const perDocumentLimit = options.perDocumentLimit == null ?
529
+ get(options, 'options.perDocumentLimit', null) :
530
+ options.perDocumentLimit;
531
+
532
+ if (!available[modelName] || perDocumentLimit != null) {
533
+ const currentOptions = {
534
+ model: Model
535
+ };
536
+ if (data.isVirtual && get(data.virtual, 'options.options')) {
537
+ currentOptions.options = utils.clone(data.virtual.options.options);
538
+ } else if (schemaOptions != null) {
539
+ currentOptions.options = Object.assign({}, schemaOptions);
540
+ }
541
+ utils.merge(currentOptions, options);
542
+
543
+ // Used internally for checking what model was used to populate this
544
+ // path.
545
+ options[populateModelSymbol] = Model;
546
+ available[modelName] = {
547
+ model: Model,
548
+ options: currentOptions,
549
+ match: data.hasMatchFunction ? [data.match] : data.match,
550
+ docs: [doc],
551
+ ids: [ids],
552
+ allIds: [ret],
553
+ unpopulatedValues: [unpopulatedValue],
554
+ localField: new Set([data.localField]),
555
+ foreignField: new Set([data.foreignField]),
556
+ justOne: data.justOne,
557
+ isVirtual: data.isVirtual,
558
+ virtual: data.virtual,
559
+ count: data.count,
560
+ [populateModelSymbol]: Model
561
+ };
562
+ map.push(available[modelName]);
563
+ } else {
564
+ available[modelName].localField.add(data.localField);
565
+ available[modelName].foreignField.add(data.foreignField);
566
+ available[modelName].docs.push(doc);
567
+ available[modelName].ids.push(ids);
568
+ available[modelName].allIds.push(ret);
569
+ available[modelName].unpopulatedValues.push(unpopulatedValue);
570
+ if (data.hasMatchFunction) {
571
+ available[modelName].match.push(data.match);
572
+ }
573
+ }
574
+ }
575
+ }
576
+
577
+ function _getModelFromConn(conn, modelName) {
578
+ /* If this connection has a parent from `useDb()`, bubble up to parent's models */
579
+ if (conn.models[modelName] == null && conn._parent != null) {
580
+ return _getModelFromConn(conn._parent, modelName);
581
+ }
582
+
583
+ return conn.model(modelName);
584
+ }
585
+
586
+ /*!
587
+ * ignore
588
+ */
589
+
590
+ function handleRefFunction(ref, doc) {
591
+ if (typeof ref === 'function' && !ref[modelSymbol]) {
592
+ return ref.call(doc, doc);
593
+ }
594
+ return ref;
595
+ }
596
+
597
+ /*!
598
+ * ignore
599
+ */
600
+
601
+ function _getLocalFieldValues(doc, localField, model, options, virtual, schema) {
602
+ // Get Local fields
603
+ const localFieldPathType = model.schema._getPathType(localField);
604
+ const localFieldPath = localFieldPathType === 'real' ?
605
+ model.schema.path(localField) :
606
+ localFieldPathType.schema;
607
+ const localFieldGetters = localFieldPath && localFieldPath.getters ?
608
+ localFieldPath.getters : [];
609
+
610
+ localField = localFieldPath != null && localFieldPath.instance === 'Embedded' ? localField + '._id' : localField;
611
+
612
+ const _populateOptions = get(options, 'options', {});
613
+
614
+ const getters = 'getters' in _populateOptions ?
615
+ _populateOptions.getters :
616
+ get(virtual, 'options.getters', false);
617
+ if (localFieldGetters.length !== 0 && getters) {
618
+ const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc);
619
+ const localFieldValue = utils.getValue(localField, doc);
620
+ if (Array.isArray(localFieldValue)) {
621
+ const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc);
622
+ return localFieldValue.map((localFieldArrVal, localFieldArrIndex) =>
623
+ localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex]));
624
+ } else {
625
+ return localFieldPath.applyGetters(localFieldValue, hydratedDoc);
626
+ }
627
+ } else {
628
+ return convertTo_id(mpath.get(localField, doc, lookupLocalFields), schema);
629
+ }
630
+ }
631
+
632
+ /**
633
+ * Retrieve the _id of `val` if a Document or Array of Documents.
634
+ *
635
+ * @param {Array|Document|Any} val
636
+ * @param {Schema} schema
637
+ * @return {Array|Document|Any}
638
+ * @api private
639
+ */
640
+
641
+ function convertTo_id(val, schema) {
642
+ if (val != null && val.$__ != null) {
643
+ return val._id;
644
+ }
645
+ if (val != null && val._id != null && (schema == null || !schema.$isSchemaMap)) {
646
+ return val._id;
647
+ }
648
+
649
+ if (Array.isArray(val)) {
650
+ const rawVal = val.__array != null ? val.__array : val;
651
+ for (let i = 0; i < rawVal.length; ++i) {
652
+ if (rawVal[i] != null && rawVal[i].$__ != null) {
653
+ rawVal[i] = rawVal[i]._id;
654
+ }
655
+ }
656
+ if (utils.isMongooseArray(val) && val.$schema()) {
657
+ return val.$schema()._castForPopulate(val, val.$parent());
658
+ }
659
+
660
+ return [].concat(val);
661
+ }
662
+
663
+ // `populate('map')` may be an object if populating on a doc that hasn't
664
+ // been hydrated yet
665
+ if (getConstructorName(val) === 'Object' &&
666
+ // The intent here is we should only flatten the object if we expect
667
+ // to get a Map in the end. Avoid doing this for mixed types.
668
+ (schema == null || schema[schemaMixedSymbol] == null)) {
669
+ const ret = [];
670
+ for (const key of Object.keys(val)) {
671
+ ret.push(val[key]);
672
+ }
673
+ return ret;
674
+ }
675
+ // If doc has already been hydrated, e.g. `doc.populate('map')`
676
+ // then `val` will already be a map
677
+ if (val instanceof Map) {
678
+ return Array.from(val.values());
679
+ }
680
+
681
+ return val;
682
+ }
683
+
684
+ /*!
685
+ * ignore
686
+ */
687
+
688
+ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normalizedRefPath, ret) {
689
+ // Re: gh-8452. Embedded discriminators may not have `refPath`, so clear
690
+ // out embedded discriminator docs that don't have a `refPath` on the
691
+ // populated path.
692
+ if (!data.isRefPath || normalizedRefPath == null) {
693
+ return;
694
+ }
695
+
696
+ const pieces = normalizedRefPath.split('.');
697
+ let cur = '';
698
+ let modelNames = void 0;
699
+ for (let i = 0; i < pieces.length; ++i) {
700
+ const piece = pieces[i];
701
+ cur = cur + (cur.length === 0 ? '' : '.') + piece;
702
+ const schematype = modelSchema.path(cur);
703
+ if (schematype != null &&
704
+ schematype.$isMongooseArray &&
705
+ schematype.caster.discriminators != null &&
706
+ Object.keys(schematype.caster.discriminators).length !== 0) {
707
+ const subdocs = utils.getValue(cur, doc);
708
+ const remnant = options.path.substring(cur.length + 1);
709
+ const discriminatorKey = schematype.caster.schema.options.discriminatorKey;
710
+ modelNames = [];
711
+ for (const subdoc of subdocs) {
712
+ const discriminatorName = utils.getValue(discriminatorKey, subdoc);
713
+ const discriminator = schematype.caster.discriminators[discriminatorName];
714
+ const discriminatorSchema = discriminator && discriminator.schema;
715
+ if (discriminatorSchema == null) {
716
+ continue;
717
+ }
718
+ const _path = discriminatorSchema.path(remnant);
719
+ if (_path == null || _path.options.refPath == null) {
720
+ const docValue = utils.getValue(data.localField.substring(cur.length + 1), subdoc);
721
+ ret.forEach((v, i) => {
722
+ if (v === docValue) {
723
+ ret[i] = SkipPopulateValue(v);
724
+ }
725
+ });
726
+ continue;
727
+ }
728
+ const modelName = utils.getValue(pieces.slice(i + 1).join('.'), subdoc);
729
+ modelNames.push(modelName);
730
+ }
731
+ }
732
+ }
733
+
734
+ return modelNames;
735
+ }
736
+
737
+ /**
738
+ * Throw an error if there are any $where keys
739
+ */
740
+
741
+ function throwOn$where(match) {
742
+ if (match == null) {
743
+ return;
744
+ }
745
+ if (typeof match !== 'object') {
746
+ return;
747
+ }
748
+ for (const key of Object.keys(match)) {
749
+ if (key === '$where') {
750
+ throw new MongooseError('Cannot use $where filter with populate() match');
751
+ }
752
+ if (match[key] != null && typeof match[key] === 'object') {
753
+ throwOn$where(match[key]);
754
+ }
755
+ }
756
+ }