【发布时间】:2019-04-09 08:07:48
【问题描述】:
**我已经在下面回答了。简而言之,即使您不直接引用它,您也需要在要填充的模块中要求模型。
在填充一个特定的 ID 数组时,我遇到了一个奇怪的 mongoose 问题。
我有三个模型,用户、公司和小部件。
当我返回拥有用户的公司时,一切都很好:
Company.findOne({ name: 'xyz' })
.populate('users')
.exec(function(err, company) {
if (err) return res.send(err)
res.send(company)
})
但是,当我尝试用“小部件”替换填充“用户”时,出现以下错误:
{
"message": "Schema hasn't been registered for model \"widget\".\nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"
}
以下是模型:
用户:
const UserSchema = new Schema({
name: String,
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
company: {
type: Schema.Types.ObjectId,
ref: 'company'
}
});
const User = mongoose.model("user", UserSchema);
公司:
const CompanySchema = new Schema({
name: String,
URL: {
type: String,
unique: true
},
users: [{
type: Schema.Types.ObjectId,
ref: 'user'
}],
widgets: [{
type: Schema.Types.ObjectId,
ref: 'widget'
}]
});
const Company = mongoose.model('company', CompanySchema);
小部件:
const WidgetSchema = new Schema({
title: {
type: String,
required: true
},
maker: String
});
const Widget = mongoose.model('widget', WidgetSchema);
我已经手动检查了公司模型的小部件数组中的_id,它们都是正确的。
【问题讨论】:
标签: mongodb mongoose mongoose-schema mongoose-populate