Skip to content

Commit

Permalink
fix(schema): handle maps of maps
Browse files Browse the repository at this point in the history
Fix #10644
  • Loading branch information
vkarpov15 committed Sep 1, 2021
1 parent d21d2b1 commit 36d23ce
Showing 1 changed file with 34 additions and 14 deletions.
48 changes: 34 additions & 14 deletions lib/schema.js
Expand Up @@ -681,21 +681,9 @@ Schema.prototype.path = function(path, obj) {
// The '$' is to imply this path should never be stored in MongoDB so we
// can easily build a regexp out of this path, and '*' to imply "any key."
const mapPath = path + '.$*';
let _mapType = { type: {} };
if (utils.hasUserDefinedProperty(obj, 'of')) {
const isInlineSchema = utils.isPOJO(obj.of) &&
Object.keys(obj.of).length > 0 &&
!utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
_mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
}
if (utils.hasUserDefinedProperty(obj, 'ref')) {
_mapType = { type: _mapType, ref: obj.ref };
}

this.paths[mapPath] = this.interpretAsType(mapPath,
_mapType, this.options);
this.paths[mapPath] = schemaType.$__schemaType;
this.mapPaths.push(this.paths[mapPath]);
schemaType.$__schemaType = this.paths[mapPath];
}

if (schemaType.$isSingleNested) {
Expand Down Expand Up @@ -1032,9 +1020,41 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
'http://bit.ly/mongoose-schematypes for a list of valid schema types.');
}

return new MongooseTypes[name](path, obj);
const schemaType = new MongooseTypes[name](path, obj);

if (schemaType.$isSchemaMap) {
createMapNestedSchemaType(this, schemaType, path, obj, options);
}

return schemaType;
};

/*!
* ignore
*/

function createMapNestedSchemaType(schema, schemaType, path, obj, options) {
const mapPath = path + '.$*';
let _mapType = { type: {} };
if (utils.hasUserDefinedProperty(obj, 'of')) {
const isInlineSchema = utils.isPOJO(obj.of) &&
Object.keys(obj.of).length > 0 &&
!utils.hasUserDefinedProperty(obj.of, schema.options.typeKey);
if (isInlineSchema) {
_mapType = { [schema.options.typeKey]: new Schema(obj.of) };
} else if (utils.isPOJO(obj.of)) {
_mapType = Object.assign({}, obj.of);
} else {
_mapType = { [schema.options.typeKey]: obj.of };
}

if (utils.hasUserDefinedProperty(obj, 'ref')) {
_mapType.ref = obj.ref;
}
}
schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options);
}

/**
* Iterates the schemas paths similar to Array#forEach.
*
Expand Down

0 comments on commit 36d23ce

Please sign in to comment.