Skip to content

Commit

Permalink
Merge pull request #14447 from Automattic/IslandRhythms/gh-14416
Browse files Browse the repository at this point in the history
fix: array schema definitions with `of` keyword
  • Loading branch information
vkarpov15 committed Mar 20, 2024
2 parents dc9810b + a8d5c98 commit 1f53635
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/schema.js
Expand Up @@ -1292,6 +1292,7 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
return clone;
}


// If this schema has an associated Mongoose object, use the Mongoose object's
// copy of SchemaTypes re: gh-7158 gh-6933
const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
Expand Down Expand Up @@ -1357,9 +1358,13 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
}
return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
}

if (Array.isArray(cast)) {
return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
if (typeof cast !== 'undefined') {
if (Array.isArray(cast) || cast.type === Array || cast.type == 'Array') {
if (cast && cast.type == 'Array') {
cast.type = Array;
}
return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
}
}

// Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })`
Expand Down Expand Up @@ -1410,7 +1415,6 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
? cast[options.typeKey]
: cast;

if (Array.isArray(type)) {
return new MongooseTypes.Array(path, this.interpretAsType(path, type, options), obj);
}
Expand Down
10 changes: 10 additions & 0 deletions test/schema.test.js
Expand Up @@ -3202,4 +3202,14 @@ describe('schema', function() {
const doc = new baseModel({ type: 1, self: [{ type: 1 }] });
assert.equal(doc.self[0].type, 1);
});
it('should have the correct schema definition with array schemas (gh-14416)', function() {
const schema = new Schema({
nums: [{ type: Array, of: Number }],
tags: [{ type: 'Array', of: String }],
subdocs: [{ type: Array, of: Schema({ name: String }) }]
});
assert.equal(schema.path('nums.$').caster.instance, 'Number'); // actually Mixed
assert.equal(schema.path('tags.$').caster.instance, 'String'); // actually Mixed
assert.equal(schema.path('subdocs.$').casterConstructor.schema.path('name').instance, 'String'); // actually Mixed
});
});

0 comments on commit 1f53635

Please sign in to comment.