Mongoose MissingSchemaError求助:关联Category模型失败排查
问题原因及解决方案
1. 模型名称大小写不匹配
你定义Category模型时,指定的模型名称为**"Categories"**(首字母大写):
let Category = mongoose.model("Categories", category);
但在Coupons模型的categoryId字段中,ref使用的是全小写的**"categories"**:
categoryId: { type: mongoose.Types.ObjectId, ref: "categories", // 此处与模型名称不匹配 },
Mongoose对模型名称的匹配是精确区分大小写的,需将ref的值修改为与模型定义完全一致的**"Categories"**:
categoryId: { type: mongoose.Types.ObjectId, ref: "Categories", },
2. 模型加载顺序问题
若项目中Coupons模型的加载/引入早于Category模型,Mongoose会找不到已注册的Category模型,同样会触发该报错。
解决方式:
- 在项目入口文件(如
app.js/server.js)中,先引入Category模型,再引入Coupons模型; - 或在Coupons模型文件顶部手动引入Category模型,确保其提前注册:
const { Category } = require('./path/to/category-model-file'); // 替换为实际文件路径
验证修改
调整后重新执行populate代码即可:
return await Coupons.find(query) .populate('categoryId') .skip(parseInt(skip)).select(select).limit(parseInt(limit)).sort({ createdAt: -1 })
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

