Skip to content

Commit

Permalink
refactor(schema): create separate schematype for DocumentArrayPaths i…
Browse files Browse the repository at this point in the history
…nstead of ad-hoc within `getPositionalPath()`

Re: #6405
  • Loading branch information
vkarpov15 committed Oct 27, 2019
1 parent 9549015 commit 7dbf96c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
11 changes: 1 addition & 10 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1179,16 +1179,7 @@ function getPositionalPathType(self, path) {

if (i === last && val && !/\D/.test(subpath)) {
if (val.$isMongooseDocumentArray) {
const oldVal = val;
val = new SchemaType(subpath, {
required: get(val, 'schemaOptions.required', false)
});
val.cast = function(value, doc, init) {
return oldVal.cast(value, doc, init)[0];
};
val.$isMongooseDocumentArrayElement = true;
val.caster = oldVal.caster;
val.schema = oldVal.schema;
val = val.$embeddedSchemaType;
} else if (val instanceof MongooseTypes.Array) {
// StringSchema, NumberSchema, etc
val = val.caster;
Expand Down
12 changes: 12 additions & 0 deletions lib/schema/documentarray.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const CastError = require('../error/cast');
const EventEmitter = require('events').EventEmitter;
const SchemaType = require('../schematype');
const discriminator = require('../helpers/model/discriminator');
const get = require('../helpers/get');
const util = require('util');
const utils = require('../utils');
const getConstructor = require('../helpers/discriminator/getConstructor');
Expand Down Expand Up @@ -54,6 +55,17 @@ function DocumentArrayPath(key, schema, options, schemaOptions) {
return arr;
});
}

const parentSchemaType = this; /* eslint consistent-this: 0 */
this.$embeddedSchemaType = new SchemaType(key + '.$', {
required: get(this, 'schemaOptions.required', false)
});
this.$embeddedSchemaType.cast = function(value, doc, init) {
return parentSchemaType.cast(value, doc, init)[0];
};
this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true;
this.$embeddedSchemaType.caster = this.Constructor;
this.$embeddedSchemaType.schema = this.schema;
}

/**
Expand Down

0 comments on commit 7dbf96c

Please sign in to comment.