diff --git a/lib/schemaType.js b/lib/schemaType.js index f95ecbb322..e5aa476468 100644 --- a/lib/schemaType.js +++ b/lib/schemaType.js @@ -1724,6 +1724,25 @@ SchemaType.prototype.clone = function() { return schematype; }; +/** + * Returns the embedded schema type, if any. For arrays, document arrays, and maps, `getEmbeddedSchemaType()` + * returns the schema type of the array's elements (or map's elements). For other types, `getEmbeddedSchemaType()` + * returns `undefined`. + * + * #### Example: + * + * const schema = new Schema({ name: String, tags: [String] }); + * schema.path('name').getEmbeddedSchemaType(); // undefined + * schema.path('tags').getEmbeddedSchemaType(); // SchemaString { path: 'tags', ... } + * + * @returns {SchemaType} embedded schematype + * @api public + */ + +SchemaType.prototype.getEmbeddedSchemaType = function getEmbeddedSchemaType() { + return this.$embeddedSchemaType; +}; + /*! * Module exports. */ diff --git a/test/schematype.test.js b/test/schematype.test.js index ad8367d0f6..725e21966a 100644 --- a/test/schematype.test.js +++ b/test/schematype.test.js @@ -315,4 +315,13 @@ describe('schematype', function() { /password must be at least six characters/ ); }); + + it('supports getEmbeddedSchemaType() (gh-8389)', function() { + const schema = new Schema({ name: String, tags: [String] }); + assert.strictEqual(schema.path('name').getEmbeddedSchemaType(), undefined); + const schemaType = schema.path('tags').getEmbeddedSchemaType(); + assert.ok(schemaType); + assert.equal(schemaType.instance, 'String'); + assert.equal(schemaType.path, 'tags'); + }); }); diff --git a/test/types/schema.test.ts b/test/types/schema.test.ts index 04828bc4f1..a2164ddaa2 100644 --- a/test/types/schema.test.ts +++ b/test/types/schema.test.ts @@ -1634,3 +1634,10 @@ function gh14825() { type SchemaType = InferSchemaType; expectAssignable({} as SchemaType); } + +function gh8389() { + const schema = new Schema({ name: String, tags: [String] }); + + expectAssignable | undefined>(schema.path('name').getEmbeddedSchemaType()); + expectAssignable | undefined>(schema.path('tags').getEmbeddedSchemaType()); +} diff --git a/types/schematypes.d.ts b/types/schematypes.d.ts index e8a0ecffdf..1e270733e4 100644 --- a/types/schematypes.d.ts +++ b/types/schematypes.d.ts @@ -229,6 +229,9 @@ declare module 'mongoose' { /** Adds a getter to this schematype. */ get(fn: Function): this; + /** Gets this SchemaType's embedded SchemaType, if any */ + getEmbeddedSchemaType(): SchemaType | undefined; + /** * Defines this path as immutable. Mongoose prevents you from changing * immutable paths unless the parent document has [`isNew: true`](/docs/api/document.html#document_Document-isNew).