1 | 'use strict';
|
2 |
|
3 | const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
|
4 | const get = require('../get');
|
5 |
|
6 | /*!
|
7 | * Like `schema.path()`, except with a document, because impossible to
|
8 | * determine path type without knowing the embedded discriminator key.
|
9 | */
|
10 |
|
11 | module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path) {
|
12 | const parts = path.split('.');
|
13 | let schematype = null;
|
14 | let type = 'adhocOrUndefined';
|
15 |
|
16 | filter = filter || {};
|
17 | update = update || {};
|
18 |
|
19 | for (let i = 0; i < parts.length; ++i) {
|
20 | const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.'));
|
21 | schematype = schema.path(subpath);
|
22 | if (schematype == null) {
|
23 | continue;
|
24 | }
|
25 |
|
26 | type = schema.pathType(subpath);
|
27 | if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) &&
|
28 | schematype.schema.discriminators != null) {
|
29 | const discriminators = schematype.schema.discriminators;
|
30 | const key = get(schematype, 'schema.options.discriminatorKey');
|
31 | const discriminatorValuePath = subpath + '.' + key;
|
32 | const discriminatorFilterPath =
|
33 | discriminatorValuePath.replace(/\.\d+\./, '.');
|
34 | let discriminatorKey = null;
|
35 |
|
36 | if (discriminatorValuePath in filter) {
|
37 | discriminatorKey = filter[discriminatorValuePath];
|
38 | }
|
39 | if (discriminatorFilterPath in filter) {
|
40 | discriminatorKey = filter[discriminatorFilterPath];
|
41 | }
|
42 | const wrapperPath = subpath.replace(/\.\d+$/, '');
|
43 | if (schematype.$isMongooseDocumentArrayElement &&
|
44 | get(filter[wrapperPath], '$elemMatch.' + key) != null) {
|
45 | discriminatorKey = filter[wrapperPath].$elemMatch[key];
|
46 | }
|
47 |
|
48 | if (discriminatorValuePath in update) {
|
49 | discriminatorKey = update[discriminatorValuePath];
|
50 | }
|
51 |
|
52 | if (discriminatorKey == null || discriminators[discriminatorKey] == null) {
|
53 | continue;
|
54 | }
|
55 | const rest = parts.slice(i + 1).join('.');
|
56 | schematype = discriminators[discriminatorKey].path(rest);
|
57 | if (schematype != null) {
|
58 | type = discriminators[discriminatorKey]._getPathType(rest);
|
59 | break;
|
60 | }
|
61 | }
|
62 | }
|
63 |
|
64 | return { type: type, schematype: schematype };
|
65 | };
|