![](/img/trans.png)
[英]Fatal error: Schema hasn't been registered for model “a”. Use mongoose.model(name, schema)
[英]Mongoose Error: Schema hasn't been registered for model "name". Use mongoose.model(name, schema)
我有兩個模型。 在第一個模型上,我有一個虛擬字段,應該由另一個(一對多關系)填充。 而且它不起作用。
型號一:
import { Schema, model } from 'mongoose';
const vendorSchema = new Schema<VendorProps>({
company_name: String,
product_type: String,
}, {
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
});
vendorSchema.virtual('campaigns', {
ref: 'campaign',
foreignField: 'vendor_id',
localField: '_id'
});
const Vendor = model<VendorProps>(
'Vendor',
vendorSchema
);
export default Vendor;
型號二:
import { Schema, model } from 'mongoose';
const campaignSchema = new Schema<CampaignProps>({
lead_volume: Number,
cost_per_credit_score: String,
vendor_id: {
type: Schema.ObjectId,
ref: 'Vendor',
},
}, {
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
});
const Campaign = model<CampaignProps>(
'campaign',
campaignSchema
);
export default Campaign;
(我省略了 Props,因為它們是 .ts 文件)
在index
文件中,我導入了引用下面控制器方法的路由:
import VendorModel from '../models/vendor';
await VendorModel.findById(id).populate('campaigns').exec();
我至少有 12 個其他類似的模型,它們的工作方式完全相同。 (當我創建這兩個 + 控制器時,我只是復制/粘貼並修改了名稱)但是由於某種原因,當我通過 ID 查詢供應商類型時,它給了我標題錯誤。
我完全被難住了。 (我在 SO 上查看了其他一些類似的線程,但沒有一個可以幫助我,因為我認為我的代碼確實沒有錯,它應該可以工作)
有任何想法嗎?
所以我不小心弄清楚了為什么這不起作用。 Campaign
模型沒有在任何地方used
(除了在填充查詢中)。
創建后,我將模型添加到現有路線(作為查詢)代碼有效。 所以基本上模型沒有“ registered
”,所以模型一引用了一個不存在的模型(如果你問貓鼬,我們是)。
tl:博士; 您必須在代碼中引用模型才能使虛擬字段工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.