NestJS Schema虚拟字段关联ProductDocument时触发MissingSchemaError问题排查求助
解决Mongoose MissingSchemaError: Schema hasn't been registered for model "ProductDocument"
这个错误的核心原因是你混淆了TypeScript类型名和Mongoose模型注册名,还有几处代码拼写错误,咱们一步步来修复:
1. 修正模型引用名称
你在@Prop和虚拟字段里用了'ProductDocument',但这只是你定义的TypeScript类型(ProductDocument),而Mongoose识别的是你注册模型时用的实际名称(比如你注册Product模型时应该是model('Product', ProductSchema),模型名是'Product')。所以要把所有ref: 'ProductDocument'改成实际的模型名。
2. 修复Schema拼写错误
你的代码最后两行用了ProductPriceSchema.set(...),但前面定义的Schema变量是PriceSchema,这是笔误,必须统一成PriceSchema。
修正后的完整代码
export type PriceDocument = Price & Document; @Schema({ timestamps: true }) export class Price { // 把ref改成实际的Product模型名,比如'Product' @Prop({ ref: 'Product', required: true }) uid: string; @Prop() standardPrice: number; @Prop({ required: true }) startDate: Date; @Prop() endDate: Date; } export const PriceSchema = SchemaFactory.createForClass<Price>(Price) .index({ uid: 1, startDate: 1, endDate: 1 }, { unique: true }); // 虚拟字段的ref同样改成正确的模型名 PriceSchema.virtual('products', { ref: 'Product', localField: 'uid', foreignField: 'uid' }); // 修正拼写错误:ProductPriceSchema → PriceSchema PriceSchema.set('toObject', { virtuals: true }); PriceSchema.set('toJSON', { virtuals: true });
额外注意事项
- 确保Product模型在Price模型之前注册:Mongoose需要先加载被引用的模型,所以你的代码里要保证Product模型的import/require顺序在Price模型之前,或者在注册Price模型前先完成Product模型的注册。
- 确认Product模型的
uid字段存在:虚拟字段关联的foreignField是Product模型里的uid,要保证这个字段存在且类型和Price的uid匹配。
这样修改后,你再执行populate('products')就不会再报Schema未注册的错误了。
内容的提问来源于stack exchange,提问作者kimfs
相关产品推荐
相关产品推荐

