如何在Mongoose Schema中使用自定义TypeScript类型
问题原因
TypeScript 中定义的type、interface都属于编译期类型,编译为 JavaScript 后会被完全擦除,不存在于运行时代码中。而 Mongoose Schema 构造函数的入参是运行时实际使用的配置对象,其中的type字段需要传入运行时存在的有效值(比如原生构造函数、其他 Mongoose Schema 实例),你直接传入仅编译期存在的Associated类型,自然会触发“类型被当作值使用”的报错。
解决方法
你需要同时维护「编译期的TS类型定义」和「运行期的Mongoose Schema定义」两部分,具体修改如下:
- 先为
Associated类型定义对应的嵌套 Mongoose Schema:
// 原TS类型定义保留,用于编译期类型校验 type Associated = { associatedId : string imei : string vehicleTypeId: string } // 新增:定义Associated对应的运行时嵌套Schema const AssociatedSchema = new Schema<Associated>({ associatedId: { type: String, required: true }, imei: { type: String, required: true }, vehicleTypeId: { type: String, required: true } })
- 修改
GroupSchema中associated字段的配置,替换为上面定义的AssociatedSchema:
interface IGroup extends Document { // ...其他字段 associated: Associated // ...其他字段 } const GroupSchema = new Schema<IGroup>( { // ...其他字段 associated: { type: AssociatedSchema, // 这里传运行时的Schema实例,不要传TS类型 required: true // 按需配置是否必填、默认值等属性 }, // ...其他字段 }, { collection: 'group' } ) const Group = model<IGroup>('Group', GroupSchema)
补充说明
- 如果
associated字段是存储多个Associated对象的数组,配置写法调整为:
associated: { type: [AssociatedSchema], default: () => [] }
- 如果不想重复定义TS类型和Schema结构,可以使用
@typegoose/typegoose库,通过装饰器同时生成运行时Schema和编译期TS类型,避免重复代码。
内容的提问来源于stack exchange,提问作者Anthony Luzquiños
相关产品推荐
相关产品推荐

