【问题标题】:MissingSchemaError while using Mongoose Populate with only one model仅使用一个模型使用 Mongoose 填充时出现 MissingSchemaError
【发布时间】: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


    【解决方案1】:

    好的,所以这代表我缺乏理解。

    在我使用的模块中:

    Company.findOne({ name: 'xyz' })
        .populate('users')
        .exec(function(err, company) {
        if (err) return res.send(err)
        res.send(company)
        })
    

    我已导入 User 模型以供模块中的其他用途。但是,由于我没有直接引用 Widget,因此我没有导入它。做了更多研究后,我发现即使不直接引用模型,您也需要在填充时导入模型。

    让我知道是否最好删除整个线程或留作参考。

    【讨论】:

    • 非常感谢,这真的很奇怪。我花了几个小时试图解决这个问题
    猜你喜欢
    • 2017-08-21
    • 2013-11-14
    • 1970-01-01
    • 2015-06-09
    • 2019-01-05
    • 2021-02-09
    • 2015-08-07
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多